From Web Component to Lit Elements

43 mins remaining
Back Next

7. Lit-html

Code Checkpoint

Code Checkpoint

Why lit-html

CFirst and foremost, the <template> tag is useful and performant, but it isn't packaged with the logic of the component thus making it difficult to distribute the template with the rest of the logic. Additionally the way template elements are used inherently lend to imperative code, which in many cases, leads to less-readable code compared to declarative coding patterns.

This is where lit-html comes in! Lit html is the rendering system of Lit that allows you to write HTML templates in Javascript, then efficiently render and re-render those templates together with data to create and update DOM. It is similar to popular JSX and VDOM libraries but it runs natively in the browser and much more efficiently in many cases.

Using Lit HTML

Next, migrate the native Web Component rating-element to use Lit template which use Tagged Template Literals which are functions that take template strings as arguments with a special syntax. Lit then uses template elements under the hood to provide fast rendering as well as providing some sanitization features for security. Start by migrating the <template> in index.html into a Lit template by adding a render() method to the webcomponent:

index.js

You may also delete your template from index.html. In this render method you define a variable called template and invoke the html tagged template literal function. You will also notice that you have performed a simple data binding inside the span.rating element by using the template literal interpolation syntax of ${...}. This means that you will eventually no longer need to imperatively update that node. Additionally, you call the lit render method which synchronously renders the template into the shadow root.

Migrating to Declarative Syntax

Now, update the view when the attribute changes; this is similar to an input updating its view when you set <input value="newValue">. Luckily, the Web Component lifecycle includes the attributeChangedCallback. Update the rating by adding the following lines:

index.js

In order for the attributeChangedCallback to trigger, you must set a static getter for RatingElement.observedAttributes which defines the attributes to be observed for changes. You then set the rating declaratively in the DOM. Give it a try:

Refresh the page, and you should have a functioning rating button that should look like this when the upvote is pressed!