Write, Run & Share Lit code online using OneCompiler's Lit online editor for free. Choose 'Lit' as the language and you'll get a small counter component to start from. The preview updates as you type, and you don't need to install anything.
Lit is a small library from Google for building web components. You write a class that extends LitElement, describe its markup with the html template tag, and the browser treats it like any built-in element. Because the result is a standard custom element, you can drop it into plain HTML or use it alongside React, Vue or any other framework.
Import Lit from a CDN inside a module script.
import { LitElement, html, css } from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';
Extend LitElement, return markup from render(), and register a tag name. Custom element names must contain a dash.
class HelloWorld extends LitElement {
render() {
return html`<p>Hello from Lit!</p>`;
}
}
customElements.define('hello-world', HelloWorld);
<hello-world></hello-world>
Properties listed in static properties re-render the component when they change. They can also be set from HTML attributes.
class GreetUser extends LitElement {
static properties = { name: { type: String } };
constructor() {
super();
this.name = 'World';
}
render() {
return html`<p>Hello, ${this.name}!</p>`;
}
}
customElements.define('greet-user', GreetUser);
<greet-user name="Lit"></greet-user>
Bind listeners with the @ prefix.
render() {
return html`<button @click=${() => this.count++}>Clicked ${this.count} times</button>`;
}
Styles in static styles only apply inside the component, thanks to the shadow DOM.
static styles = css`
p {
color: rebeccapurple;
}
`;
Templates are plain JavaScript, so use map and the ternary operator.
render() {
return html`
${this.items.length
? html`<ul>${this.items.map((item) => html`<li>${item}</li>`)}</ul>`
: html`<p>No items yet.</p>`}
`;
}