DEV Community

eleonorarocchi
eleonorarocchi

Posted on

Lit: how to use it

Lit can be easily added to existing projects:
in fact, Lit components work with any JavaScript framework, template server system and CMS.

In fact, a Lit component can be used directly in HTML, with the DOM API or in templates.
Most JavaScript frameworks have great support for Web components and Lit, just import the element definition and use the element tag names in the templates.

First, you install the Lit package from the command line, with npm:

npm i lit
Enter fullscreen mode Exit fullscreen mode

A new item can be created in any project folder, using JSX.

JSX is a language used for creating templates. It is an extension of the JavaScript syntax.

Image description

A Lit component is a reusable piece of the user interface. It is a kind of container, with a state, which displays a user interface based on its state.
It can react to user input, trigger events, whatever you can expect from a UI component.
A Lit component is an HTML element, so it has all the standard element APIs.

We create a class that extends LitElement and register it with the browser:
Image description

In TS, the @customElement decorator is an abbreviation for calling customElements.define, which registers a custom element class with the browser and binds it to an element name (in this case, simple-greeting).

Otherwise you can use JS:
Image description

By defining a Lit component, you are defining a custom HTML element; you can use the new element like any HTML element:
Image description

Image description

The base class LitElement is a sub-class of HTMLElement, therefore a Lit component inherits all properties of the standard methods of HTMLElement.

Specifically, LitElement inherits from ReactiveElement,
which implements reactive properties, and in turn inherits from HTMLElement.

TypeScript infers the class of an HTML element returned by some DOM APIs based on the tag name.

For example, we know that document.createElement ('img') returns an HTMLImageElement instance with an src property of type string.

Custom elements can get the same treatment by adding the mapping with HTMLElementTagNameMap.

Image description

In this way, the following code performs the type checks correctly:
Image description

It is a good idea to add an HTMLElementTagNameMap entry to all elements
created in TypeScript and publish the .d.ts types in the npm package.

See here

Top comments (0)