Web components

Web Components is a suite of different technologies allowing you to create reusable custom elements and integrate them in HTML pages.

Custom Elements

To register your new component to the browser, you will need the Custom Elements API.

window.customElements.define('my-component', MyComponent);

Then, you will be able to integrate your component within your HTML markup.

<html>
    <body>
        <my-component name="John" />
    </body>
</html>

or from your javascript code as you would do to create a standard HTML element

document.createElement("my-component")

LitElement

LitElement inherit from HTMLElement class and will help us to create Web Components.

import {html, css, LitElement} from 'lit';

export class MyComponent extends LitElement {
  static styles = css`p { color: blue }`;

  static properties = {
    name: {type: String},
  };

  constructor() {
    super();
    this.name = 'Somebody';
  }

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

Shadow DOM

Shadow DOM is a set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.

By default, Lit use the Shadow DOM to render your HTML markup. This is why your css style will be scoped to markup defined inside your component and won't affect other tags of the HTML document.

Last updated