Back to Lit

01

packages/lit-dev-content/site/tutorials/content/intro-to-lit/01.md

latest1.9 KB
Original Source

In Lit, most things start with defining a component. Here we've given you a starter project that has the required imports and nothing else.

  • Define a component.

    {% switchable-sample %}

    ts
    @customElement('my-element')
    export class MyElement extends LitElement {
    }
    
    js
    export class MyElement extends LitElement {
    }
    customElements.define('my-element', MyElement);
    

    {% endswitchable-sample %}

    The MyElement class provides the implementation for your new component. <ts-js><span slot="ts">The <code>@customElement</code> decorator registers it with the browser as a new element type named <code>my-element</code>.</span><span slot="js">The <code>customElements.define</code> call registers it with the browser as a new element type named <code>my-element</code>.</span></ts-js>

    The "TODO" text should disappear from the Result pane, showing that the component is defined. But your component is still missing something—it doesn't display anything.

  • Add a render() method to your class.

    ts
    render() {
      return html`
        <p>Hello world! From my-element.</p>
      `;
    }
    

    The render() method defines your component's internal DOM. The html tag function processes a template literal and returns a TemplateResult—an object that describes the HTML for Lit to render. Every Lit component should include a render() method.

You should see the greeting message in the Result pane.

{% aside "info" %}

Decorators.

The TypeScript version of this code uses the @customElement decorator to register your class with the browser as a new element. The JavaScript version uses customElements.define() to do the same thing. This is a matter of style. You can use decorators—or not use decorators—in either language. For more information, see Decorators.

{% endaside %}