1. Component definition
  2. Styles
  3. Properties and state
  4. Event handlers
  5. Pass data down
  6. Pass data up

Component definition

Create a component

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`...`.

Import a component

To use a component, import its file.

👉 Important rules

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).

Styles

Add styles

Add styles by defining the static styles property. Write CSS in the css tag.

Styles are scoped

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.

Add classes

To conditionally apply styles, use classMap.

Properties and State

Define state

Use @state to define a state variable.

When the state changes, Lit will re-render any part of the component that references the state.

Define a property

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).

Event handlers

Add an event handler

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 an event handler to the component itself

Add event handlers to the component itself in the constructor() method.

Pass Data Down

Properties

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 Up

Events

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)}.