Web Development Tools

How to Create Custom Web Components Using Lit for Reusable UI Elements

Creating custom, reusable web components with Lit offers a powerful way to build encapsulated UI elements that integrate smoothly with modern web projects. This guide walks you through setting up a Lit starter project, defining LitElement-based components with reactive properties, using shadow DOM for encapsulation, styling with scoped CSS, and verifying your components work as expected.

Along the way, you’ll learn how Lit balances reusability with framework compatibility and what browser and tooling requirements to keep in mind.

Cats interacting with tech equipment (monitors, servers, coding interfaces) in minimalist wireframe environments.: How to Create Custom Web Components Using Lit for Reusable UI Elements

Quick answer

Start by ensuring Node.js and npm are installed; these manage Lit’s dependencies. Use the official Lit starter kits—JavaScript for no build step or TypeScript if you want typed components (TypeScript requires building).

After installing dependencies with npm i and building if needed (npm run build), launch the local dev server (npm run serve) to preview your components.

Define components by extending LitElement, implement a render() method returning a Lit template, and register your element with a unique tag using the @customElement decorator or customElements.define(). Declare reactive properties with @property() or static properties to enable automatic updates.

Lit renders components into an open shadow root by default for DOM and style encapsulation; include <slot> elements to allow consumer content.

Style your components within the styles static field using Lit’s css template literal. Use CSS custom properties to enable theming across shadow boundaries.

Ensure testing in browsers that support these modern APIs, as Lit 3 does not support older browsers like IE11 or Classic Edge.

Step-by-step guide

Prerequisites

Before diving into building custom web components with Lit, you need to ensure your environment is ready and your project is set up appropriately. First, confirm that your development machine has Node.js and npm installed, as these are essential for managing Lit and its dependencies.

Next, choose the official Lit starter kit—JavaScript if you prefer no build step or TypeScript if you want typed components, noting the latter requires a build process.

Also, make sure your target browser is modern and supports Web Components features like custom elements and shadow DOM. Lit 3 targets ES2021 and does not support older browsers like Internet Explorer 11 or Classic Edge, so testing in a compatible environment is crucial.

Finally, if integrating Lit into an existing npm project, install it with npm to keep dependencies managed cleanly. These steps ensure your setup supports the encapsulation, reactivity, and modularity Lit provides for reusable UI components.

Sources: Starter kits – Lit; Adding Lit to an existing project – Lit; Reactive properties – Lit; Working with Shadow DOM – Lit; Requirements – Lit.

Set Up a Lit Starter Project

To set up a new Lit project, start by downloading the official Lit JavaScript or TypeScript starter kit from the Lit documentation site. After extracting the starter kit, open a terminal in the project folder and run npm i to install the required dependencies.

For the TypeScript starter, you also need to build the project by running npm run build before starting the development server.

Once dependencies are installed (and built if TypeScript), launch the local dev server with npm run serve. This command will start a local server, and the terminal will display the URL to open in your browser, often something like http://localhost:8000/dev/.

Opening this URL should show a demo page verifying your Lit project is running correctly.

This setup gives you a ready environment to develop reusable web components with Lit, leveraging a modern toolchain and local preview. If the demo page loads successfully, you can proceed to creating and customizing your components within this project structure.

Sources: Starter kits – Lit.

Create a Custom LitElement Component

Once your Lit project is set up, creating a custom component involves extending the LitElement base class. Begin by importing LitElement and html from the Lit package.

Then, define a new class that inherits from LitElement and implement a render() method that returns an HTML template using Lit's html tagged template literal.

After defining your class, register it as a custom element by associating a unique tag name using either the @customElement('my-element') decorator from lit/decorators.js or by calling customElements.define('my-element', MyElement). This step is essential because it tells the browser to recognize your new element by that tag name, enabling its use in your HTML just like any built-in element.

For example, a simple component might look like this:

import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('my-element')
class MyElement extends LitElement {
  render() {
    return html`<p>Hello from my custom element!</p>`;
  }
}

Using the decorator requires appropriate tooling support for decorators in your build setup, but as an alternative, you can register your component with:

customElements.define('my-element', MyElement);

Once registered, your custom element can be used anywhere in your HTML by including <my-element></my-element>. This approach creates encapsulated, reusable UI elements that integrate smoothly into existing web projects or frameworks.

Sources: Adding Lit to an existing project – Lit.

Add Reactive Properties to the Component

Adding reactive properties is key to making your Lit components update automatically when their data changes. You declare these properties either using the @property() decorator or a static properties object inside your component class.

This tells Lit to watch these properties for changes and trigger updates accordingly.

For example, using the decorator looks like this:

import {property} from 'lit/decorators.js';

@property({type: String})
myProp = '';

Reactive properties work as JavaScript inputs, and Lit also maps them to corresponding HTML attributes if needed. However, attributes are string-based; for complex types like objects, you should pass data via properties rather than attributes.

Boolean properties exposed as attributes should default to false.

This setup ensures your component reflects state changes in the UI without manual DOM manipulation, making your components responsive and easy to use in markup or code.

Sources: Reactive properties – Lit.

Use Shadow DOM and Slots for Encapsulation and Composition

Lit uses shadow DOM by default to encapsulate a component’s internal DOM structure and styling from the rest of the page. When you create a LitElement component, it renders its template inside an open shadow root automatically.

This means DOM nodes and CSS rules are scoped to the component, preventing unwanted side effects on the surrounding page.

To allow consumers of your component to pass in custom content, include one or more <slot> elements in your template. Slots act as placeholders where external HTML or elements insert themselves inside your component’s shadow DOM.

This supports composition and flexible usage.

If you override the createRenderRoot() method to return the element itself instead of a shadow root, your component renders in the light DOM. That disables encapsulation and slot behavior, exposing internal styles and DOM.

Usually, it’s best to keep the default shadow DOM pattern for clean scoping.

To verify, use modern browsers that support shadow DOM natively. You can inspect the component in dev tools and see its shadow root with encapsulated markup and styles separated from the document.

This approach helps build reusable, maintainable UI components without CSS or DOM conflicts.

Sources: Working with Shadow DOM – Lit (https://lit.dev/docs/components/shadow-dom/)

Sources: Working with Shadow DOM – Lit.

Apply Scoped Styles with CSS Custom Properties

In Lit, you define your component's CSS styles using a static styles field inside your LitElement class, leveraging Lit’s css tagged template literal. These styles are scoped exclusively to the component's shadow root, ensuring they don't leak out or clash with other page styles.

To support theming and make your component adaptable, use CSS custom properties (variables). Consumers can override these custom properties from outside the shadow DOM, effectively customizing the component’s appearance without breaking encapsulation.

For example, define colors or sizes using var(--your-custom-property) in your styles.

Avoid using unsafeCSS unless you are sure the CSS content is trusted, since injecting untrusted styles this way can create security vulnerabilities. This discipline helps maintain safe and predictable component styling.

By applying styles this way, you gain encapsulation, reusability, and a clear, documented path for consumers to theme your components, fitting nicely into modern web app architectures.

Sources: Styles – Lit.

Verify Component Functionality and Rendering

To verify your Lit component functions correctly, open the local development server URL provided by the starter kit, typically something like http://localhost:8000/dev/, in a modern browser that supports Web Components APIs including shadow DOM and custom elements. You should see your component rendered with the expected HTML content and styling applied as defined in its template and static styles.

Next, test the reactivity by changing the component’s reactive properties through JavaScript or by updating corresponding HTML attributes if applicable. When these properties update, Lit should schedule a re-render automatically, reflecting the changes in the UI without manual DOM manipulation.

Inspect your component using browser developer tools to confirm it uses a shadow root, which scopes its DOM and CSS styles, ensuring encapsulation from the main document. If you included <slot> elements, verify that any consumer-provided content appears properly within the component.

If the component does not render or update as expected, double-check that you've correctly declared reactive properties with @property() or a static properties field, and that your browser supports the necessary Web Components features. This step ensures your Lit component works as a reusable, encapsulated UI element in supported environments.

Sources: Starter kits – Lit; Reactive properties – Lit; Working with Shadow DOM – Lit.

Troubleshooting Common Issues

When troubleshooting Lit-based web components, first verify you have all necessary tooling like Node.js and npm installed; missing these can block dependency installation and project builds. Ensure your custom element registration is correct—either use the @customElement decorator supported by your build tooling or explicitly call customElements.define() with a unique tag name.

Check that you’re testing in a modern browser supporting Web Components APIs, including custom elements and shadow DOM, since Lit 3 doesn’t work in Internet Explorer 11 or Classic Edge. If your component doesn’t update when expected, review reactive property declarations: use @property() or a static properties object to enable Lit’s update cycle.

Remember that HTML attributes are string-based, so complex data should be passed via properties rather than attributes.

By focusing on these areas—tooling, registration, browser compatibility, and reactive properties—you can resolve many common pitfalls and get your Lit components rendering and updating as intended.

Sources: Adding Lit to an existing project – Lit; Reactive properties – Lit; Requirements – Lit.

Next steps

If you want to create efficient, reusable web components, using Lit with its official starter kits is a solid choice. Just make sure to have the right environment—Node.js, npm, and a compatible modern browser.

Define your components by extending LitElement with reactive properties, use its default shadow DOM for encapsulation, and style your elements with scoped CSS and custom properties.

Test your component through the local dev server to ensure rendering and updates work as expected. Keep in mind Lit 3’s limitation regarding older browsers.

Following these guidelines strikes a good balance between reusability and integration flexibility in modern web infrastructure.