Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Lit Component

Build your first Lit component step by step. Learn the anatomy of a LitElement class: properties, styles, render, events, and how to use the finished element in HTML.

In this lesson you build a real Lit component from scratch and take it apart piece by piece. By the end you will be able to read any simple Lit element and know what each line does. We use plain JavaScript with no build step, so everything runs in the live editors on this page.

Every example imports Lit from a single file on a CDN. In a real project you would install the lit package instead; Setup, CDN and Tooling covers that. The import line looks like this:

JavaScript
import { LitElement, html, css } from "https://cdn.jsdelivr.net/gh/lit/[email protected]/all/lit-all.min.js";

The anatomy of a LitElement

Here is a complete component, a greeting that changes with a name attribute. Try changing the name on the second tag, or add a third one.

A greeting component

The component has five parts. Every Lit element you will meet has the same five.

flowchart TD
  A["class UserGreeting extends LitElement"] --> B["static properties<br/>declares reactive data"]
  A --> C["static styles<br/>scoped CSS"]
  A --> D["constructor<br/>sets default values"]
  A --> E["render()<br/>returns the template"]
  A --> F["customElements.define<br/>registers the tag name"]

The five parts of a typical Lit component.

1. The class

class UserGreeting extends LitElement gives you everything: it is a custom element (it extends HTMLElement underneath), it creates a shadow root, and it re-renders when properties change. Class names use PascalCase by convention, tag names use kebab-case.

2. Reactive properties

static properties lists the properties that should trigger a render when they change. Each entry is an options object. type: String tells Lit how to convert the HTML attribute name="Ada" into a JavaScript string. Other converters are Number and Boolean. You will explore all the options in the Reactive Properties chapter.

By default a property is linked to an attribute of the same name in lowercase, so <user-greeting name="Ada"> sets this.name to "Ada". You can also set the property from JavaScript: document.querySelector("user-greeting").name = "Grace" and the component updates.

3. Static styles

static styles takes the result of the css tag. Lit attaches it once to the shadow root. The selector :host refers to the element itself, which is how a component styles its own outer box. By default a custom element is display: inline, so most components set display: block or inline-block on :host. Styling gets its own chapter, starting with Styling Lit Components.

4. The constructor

Put default values in the constructor, after calling super(). Setting a property here does not cause an extra render, because the component has not been connected yet. An unset property is undefined, which would print the word "undefined" in a template, so give every property a sensible default.

5. The render method

render() returns a template made with the html tag. It runs the first time the element is connected and again every time a reactive property changes. Treat it as a function of the component's state: given the same properties, it should always describe the same output, with no side effects.

Registering the element

customElements.define("user-greeting", UserGreeting) connects the tag name to the class. Run it exactly once per tag name. Defining the same name twice throws an error, which is a common problem when a script is accidentally loaded twice. Note that the tag has a hyphen, as the standard requires.

Handling events

Lit templates attach event listeners with the @ prefix. The handler is a normal function, and inside a method it is automatically bound to the component, so this works as you expect.

A tip calculator

Three details in this example are worth noticing.

  • .value=${this.bill} with a leading dot sets the DOM property value, not the attribute. For form controls you almost always want the property. Lit Templates and Bindings explains the four binding types.
  • @input=${this.onBill} adds an input listener. Lit calls it with this set to the component.
  • get tip() is a normal getter. It is not a reactive property because it is derived from two that are. When either changes, render() runs again and reads a fresh value.

Using the element

Once defined, you use the component like any other tag, in HTML, in a CMS, in JavaScript or inside another component's template:

HTML
<user-greeting name="Grace"></user-greeting>
JavaScript
const el = document.createElement("user-greeting");
el.name = "Linus";
document.body.append(el);

Always write the closing tag. Custom elements cannot be self-closing, so <user-greeting /> does not do what you expect.

TypeScript and decorators

You will often see Lit written in TypeScript with decorators. The shape is the same; the decorators replace static properties and the define call:

TypeScript
import { LitElement, html, css } from "lit";
import { customElement, property } from "lit/decorators.js";

@customElement("user-greeting")
export class UserGreeting extends LitElement {
  @property() name = "stranger";

  static styles = css`:host { display: block; }`;

  render() {
    return html`Hello, ${this.name}!`;
  }
}

This track uses the plain JavaScript form, because it runs in the browser without a compiler and shows exactly what the decorators generate. Everything you learn transfers directly.

If your component renders nothing, check the browser console for two common causes: the tag name has no hyphen, or customElements.define was never reached because of an earlier error in the module.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do you put default values for reactive properties in plain JavaScript?

    Set defaults in the constructor after calling super(); this does not trigger an extra render.
  2. 2. What does :host select inside static styles?

    :host targets the element that owns the shadow root, so a component can style its own outer box.
  3. 3. What does the leading dot in .value=${this.bill} mean?

    A dot prefix is a property binding; it assigns element.value directly.
  4. 4. Which tag name can you pass to customElements.define?

    Custom element names need a hyphen and must be lowercase.
  5. 5. Why does render() have to stay free of side effects?

    render() re-runs after every update, so it should only describe output for the current state.

Summary

  • A Lit component is a class extending LitElement that is registered with customElements.define.
  • static properties declares reactive data, static styles holds scoped CSS and render() returns an html template.
  • Set defaults in the constructor and style the element's outer box with :host.
  • @event=${handler} adds listeners and .prop=${value} sets DOM properties.
  • Always include a hyphen in the tag name and always write the closing tag.

Next: Setup, CDN and Tooling