A cheat sheet for learning the basics of Lit, the JavaScript library for building web components. By Steven Traversi.
LitElement
is the base class for all components.
@customElement
is where you define the name of your component.
render
is where you define your component's view.
Write HTML in html`...`
.
To use a component, import its file.
Components are global HTML elements, you can't have more than one with the same name on a page. People are working on that though!
Components must have dashes in their name (defined using @customElement
).
Add styles by defining the static styles
property. Write CSS in the css
tag.
Styles only apply to the current element. That means you can feel free to use super generic selectors that you'd normally have to make up class names for.
To conditionally apply styles, use classMap
.
Use @state
to define a state variable.
When the state changes, Lit will re-render any part of the component that references the state.
Use @property
to define a state variable that can be accessed externally.
When the property changes, Lit will re-render any part of the component that references the property (just like state).
Add an event handler to a component using @click=${handler}
. This is the same as adding an event listener like this: el.addEventListener('click', handler)
. The handler will be called with the event object as the first argument.
Add event handlers to the component itself in the constructor()
method.
Pass data to child elements using property bindings, like this: .name=${"Steven"}
. The value can be any expression.
For boolean properties, use a question mark instead of a period, like this: ?programmer=${true}
.
You can only bind to properties declared with @property
, not @state
.
Pass data to ancestor elements using events. To emit an event, use this.dispatchEvent
.
dispatchEvent
takes an event object as the first argument.
Construct an event object like this: new CustomEvent('event-name', { detail: data, bubbles: true })
.
Provide data you want to pass to ancestors in the detail
property of the event.
Ancestors can react to the event by adding an event listener to the component, like this: @event-name=${e => this.handler(e)}
.