Build a Lightweight Web Component with Lit.js

0
38
Build a Lightweight Web Component with Lit.js


As the demand for web applications has drastically increased, the need for frameworks that can help developers speed up development becomes more demanding. Such frameworks save developers the time they would have spent reinventing the wheel. In this tutorial, you’ll learn how to build lightweight web components using Lit.js.

Without much delay, let’s get started!

What is Lit?

Lit is a simple library that can be used to create lightweight components. Lit components are incredibly adaptable and can be used across multiple apps and websites, even if those applications and websites are built on different front-end stacks. According to the documentation, Lit has various excellent features worth working with. They include:

  • Speed: Lit adds just what you need to be happy and productive by building on top of the Web Components standards: reactivity, declarative templates, and a handful of thoughtful features to reduce boilerplate and make your job easier. Every Lit component is meticulously designed with web platform evolution in mind.
  • Fast: Lit has a minified bundle and a compressed size of 5 kb. This small size allows you to keep your bundle small and thus make your application load faster. Lit also renders UI quickly because it only touches the dynamic parts of your UI when updating, eliminating the need to rebuild a virtual tree and diff it with the DOM.
  • Future Ready: Every Lit component is a native web component with the ability to communicate with other members. Web components can be used with any HTML framework or with none. Lit is thus ideal for developing shareable components, design systems, and scalable, future-proof websites and apps.

Installing Lit

This is a hands-on demonstration tutorial; before getting started, ensure you have Node.js installed. The code for this tutorial is available here on Github; feel to clone and follow along.

You need to install Lit on your computer. To do that, run the command below:

The above command will take some time to complete. However, once completed, it’s time to scaffold a lit project.

Creating a Lit project

To create a Lit project, choose the starter kit for your project from the Lit official documentation to get started with Lit. For the demonstration in this tutorial, we’ll use the Javascript starter kit. (The other possible kit is for Typescript.) So select the Javascript starter kit and click on the Use this template button. You’ll be redirected to create a new repository for the project. Call it Lit-demo and click the Create repository from template button. Now clone the project to your local computer with the command below:

1git clone https://github.com/lit/lit-element-starter-js.git

Then change the directory to the project folder and install the project dependencies.

1cd lit-demo && npm install

Now run the application with the below command.

You may delete the dev, dev-src, and docs folders.

Creating App Components

Now open and replace the code in the my-element.js file with the code snippet below:

1import { LitElement, html } from "lit";

2

3class App extends LitElement {

4 render() {

5 return html`

6 <div class="container">

7 <div class="main">

8 <h4>Daily Hobby</h4>

9 <ul>

10 <li>Coding</li>

11 </ul>

12 <div class="input-container">

13 <input type="text" placeholder="Add a hobby" />

14 <button>Add Hobby</button>

15 </div>

16 </div>

17 </div>

18 `;

19 }

20}

21customElements.define("my-element", App);

In the above code snippet, we created our App component and rendered some content to the user using the render method. First, the HTML tag function processes a template literal and returns a TemplateResult. Then, we use the @customElement decorator to register our component with the browser as a new element type named my-element. Now replace the code in the index.html file with the code snippet below:

1<!DOCTYPE html>

2<html>

3 <head>

4 <script type="module" src="my-element.js"></script>

5 <style>

6 body {

7 font-family: 'Open Sans', sans-serif;

8 font-size: 1.5em;

9 padding-left: 0.5em;

10 }

11 </style>

12 </head>

13 <body>

14 <my-element></my-element>

15 </body>

16</html>

Here, we added our component to the page with simple HTML tags.

Creating reactive properties

Now let’s add some properties to our application. First, we create properties to hold our hobbies and the value of hobbies from the form field. Update my-element.js file, adding the code snippet below:

1static properties = {

2 value: { type: String },

3 hobbies: { type: Array },

4 };

We defined the static property object in the code snippet to store our app properties. All javascript properties in Lit are defined inside this properties object. Next, we also need a constructor method in our App component class to set an initial value for the properties we created in the above snippet.

1constructor() {

2 super();

3 this.value = "";

4 this.hobbies = [

5 { text: "Reading" },

6 { text: "Eating" },

7 { text: "Cooking" },

8 ];

9 }

In the above code snippet, we assigned initial values to the value and hobbies properties.

The complete code for the component so far is as follows.

1class App extends LitElement {

2 static properties = {

3 value: { type: String },

4 todos: { type: Array },

5 };

6

7 constructor() {

8 super();

9 this.value = "";

10 this.todos = [{ text: "Reading" }, { text: "Eating" }, { text: "Cooking" }];

11 }

12

13 render() {

14 return html`

15 <div class="container">

16 <div class="main">

17 <h4>Daily Hobbies</h4>

18 <ul>

19 ${this.todos.map((item) => html`<li>${item.text}</li>`)}

20 </ul>

21 <div class="input-container">

22 <input

23 type="text"

24 placeholder="Add a hobby"

25 .value=${this.value}

26 @input=${(e) => (this.value = e.target.value)}

27 />

28 <button @click=${this.addHobbie}>Add Hubbie</button>

29 </div>

30 </div>

31 </div>

32 `;

33 }

34}

35customElements.define("my-element", App);

Open Source Session Replay

OpenReplay is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.

replayer.png

Happy debugging for modern frontend teams – start monitoring your web app for free.

Styling the App

Now let’s add some stylings to the application to make things look more appealing. Update my-element.js file with the code snippet below:

1import { LitElement, html, css } from "lit";

2

3class App extends LitElement {

4 static properties = {

5 value: { type: String },

6 todos: { type: Array },

7 };

8

9 static styles = css`

10 * {

11 box-sizing: border-box;

12 padding: 0;

13 margin: 0;

14 font-family: sans-serif;

15 }

16

17 .container {

18 background-color: #f0f0f0;

19 height: 100vh;

20 display: flex;

21 flex-direction: column;

22 align-items: center;

23 justify-content: center;

24 }

25 .main {

26 width: 50%;

27 }

28 .input-container {

29 display: flex;

30 }

31 ul {

32 list-style: none;

33 margin-top: 20px;

34 margin-bottom: 10px;

35 color: green;

36 text-align: left;

37 width: 100%;

38 font-size: 17px;

39 }

40 h4 {

41 text-align: center;

42 }

43 input {

44 width: 100%;

45 padding: 10px;

46 }

47 `;

48

49 constructor() { ... }

50

51 render() { ... }

52}

53customElements.define("my-element", App);

In the above code snippet, we imported the CSS module from Lit and defined the static styles class field to style our component.

Create App methods

Now let;‘s add a method to our application to add a new hobby to our hobbies list. Update my-element.js file with the code snippet below:

1addHobbie() {

2 const hobby = this.value;

3 this.todos.push({

4 text: hobby,

5 completed: false,

6 });

7 this.value = "";

8 this.requestUpdate();

9 }

In the above code snippet, we created an addHobbie method, and we used the array push method to a hobby using the value from the form field. Then we used the requestUpdate method to update the component to update. This way, we can see the hobbies created once the button is clicked.

Adding event listeners

Now let’s add an event listener to our component to make our application interactive. But before that, let’s loop through all the hobbies and display them in our application with the code snippet below:

1<ul>

2 ${this.todos.map((item) => html`<li>${item.text}</li>`)}

3</ul>

Then bind the value entered by the user to the input field and update the value once a user changes the value in the input field.

1<input type="text" placeholder="Add a hobby" .value=${this.value} @input=${(e) => (this.value = e.target.value)}/>

Next, we add an onclick listener to our button and bind the addHobbie method to it.

1<button @click=${this.addHobbie}>Add Hubbie</button>

In the end, our App component should look like the code snippet below:

1import { LitElement, html, css } from "lit";

2

3class App extends LitElement {

4 render() {

5 return html`

6 <div class="container">

7 <div class="main">

8 <h4>Daily Hobbies</h4>

9 <ul>

10 <li>Coding</li>

11 </ul>

12 <div class="input-container">

13 <input type="text" placeholder="Add a hobby" />

14 <button>Add hobby</button>

15 </div>

16 </div>

17 </div>

18 `;

19 }

20}

21customElements.define("my-element", App);

Test Application

Now go ahead and test the application by adding a new hobby; you should see a similar output to the screenshot below on your browser.

Our final component

Conclusion

You’ve learned how to build a lightweight web component using Lit by building a hobbies demo application.js. First, we started with an introduction to Lit. Then we discussed why you should use it in your application, and we built a demo application to explore its features. Now you may use Lit in your next project; you can learn more about Lit and add more features to the demo application you just created.



Source link

Leave a reply

Please enter your comment!
Please enter your name here