Back to Lit

01

packages/lit-dev-content/site/tutorials/content/word-viewer/01.md

latest2.2 KB
Original Source

Define a Lit component by creating a class extending LitElement and registering your class with the browser:

{% switchable-sample %}

ts
@customElement('word-viewer')
export class WordViewer extends LitElement { /* ... */ }
js
export class WordViewer extends LitElement { /* ... */  }
customElements.define('word-viewer', WordViewer);

{% endswitchable-sample %}

<ts-js> <div slot="ts">

The TypeScript @customElement decorator is a shorthand for the JavaScript equivalent of calling customElements.define, which registers the custom element class with the browser and associates it with the custom element name word-viewer.

</div> <div slot="js">

customElements.define registers the custom element class with the browser and associates it with the custom element name word-viewer.

</div> </ts-js>

{% aside "positive" %}

A valid custom element name must contain a hyphen.

This ensures forward compatibility with future tags added to HTML or SVG which won't add hyphen containing elements.

{% endaside %}

Rendering

A Lit component's render() method returns a template. Lit templates use the html tagged template literal to run without a build step in JavaScript.

Add a template to define what word-viewer should render:

ts
import { html, LitElement } from 'lit';
...

  render() {
    return html`<pre>A super expressive and efficient template!</pre>`
  }
<ts-js> <div slot="ts">

Providing good TypeScript types

If using TypeScript, you can register your custom element on the HTMLElementTagNameMap.

ts
declare global {
  interface HTMLElementTagNameMap {
    "word-viewer": WordViewer;
  }
}

Doing this allows TypeScript to infer the type of document.createElement('word-viewer') as your WordViewer class.

</div> <div slot="js"><!-- Nothing to show for JS --></div> </ts-js>

Result

You should see A super expressive and efficient template! rendered in the preview.