Why LitElement

Permalink to "Why LitElement"

There are still ways the code can be improved:

  1. If the vote property or attribute is changed, the rating property may also be changed which will result in calling render twice. Despite repeat calls of render being a very efficient, the browser is still needlessly calling that function twice.
  2. It is tedious adding new properties and attributes as it requires a lot of boilerplate code.

This is where LitElement comes in!

LitElement is Lit's base class for creating fast, lightweight web components that can be used across frameworks and environments. Next, take a look at what LitElement can do for the <rating-element>!

Defining A LitElement

Permalink to "Defining A LitElement"

Start by importing and subclassing the LitElement base class from the lit package. , and use the @customElement decorator to replace the customElements.define call.

rating-element.

Permalink to "rating-element."

What's changed?

The css tag function allows you to define CSS tagged template literals, which enable math, templating, and other features under the hood.

For a comprehensive list of styling features, refer to the Lit Styles documentation.

Styling With Lit

Permalink to "Styling With Lit"

Next, move the styles from the render method to Lit's static stylesheet:

rating-element.

Permalink to "rating-element."

This is where most styles live in Lit.

Where available, Lit uses browser features such as Constructable Stylesheets to provide faster rendering times for your styles.

Render

Permalink to "Render"

Next, render() is a LitElement lifecycle method which requires us to return a Lit template and no longer needs to check for the shadow root:

rating-element.

Permalink to "rating-element."

Now you have a styled element! In the next step you will make the element react to property and attribute changes.