Introduction to HTML Web Components 💻📝
Tags: webdev, javascript, html, beginners
Published: 2024-02-18 15:26:07

The HTML Web Components are **reusable, custom HTML elements** which you can define and create yourselves, and can be used anywhere within your HTML code. 

As web developers, we know that creating a template and reusing that wherever possible is a good programming approach. This problem was solved by JavaScript UI libraries like **[React](https://react.dev/)**. But, in some use cases, adopting to React or other JavaScript libraries is not the requirement, and using plain HTML can accomplish this task now as well.


![HTML logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mxq1ivw1asaq4r51hloy.jpg)

In 2024, the Browser support for Web Components is very enhanced. In this article, I will describe the basics of Web Components and demonstrate creating a basic Web Component as well.

## What is a Web Component?
A Web Component is a custom HTML element that you can define with your **own tag name**. It is a reusable piece of code, which can be created and incorporated easily within your HTML application.
It is basically a set of **JavaScript APIs** that allow you to define custom elements and behavior, which can then be used as desired in your UI.

**Basics of Web Components**
To create a Web Component, you must first define a **[ES2015](https://babeljs.io/docs/learn)** Class to control the element. The class can be named anything, but it is advisable to **name the Class similar to the purpose you are creating the component for**. For example, if you are creating a **Footer component**, you should name your Class as "**Footer**".

The class that you create must extend from the **[HTMLElement interface](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement)**. After doing this, you need to register your component with the browser by executing **customElements.define**.

You can refer below to see the basic structure of the Web Component - 

```
class MyComponent extends HTMLElement {
	// component implementation code written here
}

customElements.define('my-component', MyComponent);
```
An important part to note is, there is a **hyphen** in the name "**my-component**". This hyphen is required in the specification so that we can differentiate the custom Web Components from the standard HTML elements.

## Lifecycle Callbacks of the Web Components
The HTML Web Components have some **Lifecycle Callback methods** which are executed when the Browser calls the different parts of the component's lifecycle. These methods are - 

- **connectedCallback**: this method is executed when the component is first **mounted/loaded onto the DOM**.

- **disconnectedCallback**: this method is executed when the component is **unmounted/removed from the DOM**.

![Web Components as tech](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnl76edbriywguq8382n.png)

To create the Web Component, initialize the component class and execute the call to **customElements.define** method - 

```
// creating a class for the component by extending from the HTMLElement class
class CurrentDate extends HTMLElement {
    constructor() {
        super();
    }

    // calling the connectedCallback() lifecycle method of web components
    // it is executed when the components first mounts/loads on the page
    connectedCallback() {
        const date = new Date();

        this.textContent = date.toLocaleDateString();
    }
}

// registering the component to the CustomElement Registry
// the name of the custom component should always include a hyphen(-)
// this distinguishes it from the other official HTML elements
customElements.define('current-date', CurrentDate);
```
Since you are extending from the **HTMLElement** class, you have access to the **textContent** method, which is being used here to display the current date.

## How to use the Web Component?
To use your custom Web Component, you can simply import it using the **script tag** in your HTML file - 

```
<script src="./current-date.js"></script>
```
To use it in your HTML file, you can simply render the component within the HTML tags - 

```
<h2>Today's date is - </h2>
<current-date></current-date>
```
To summarize, your full HTML file will look like this - 

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Components tutorial</title>
    <script src="./current-date.js"></script>
</head>
<body>
    <h1>Introduction to Web Components</h1>

    <h2>Today's date is - </h2>
    <current-date></current-date>
</body>
</html>
```
You should see this output on your browser - 

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en5vre2b1mqgg7zch7kv.PNG)

One of the most important benefits of using the HTML Web Components is that they are **not dependent on any third-party libraries**, so using them won't have any side-effects and they won't have a significant effect on your bundle size.

And that's it! You have successfully learnt about Web Components and how to incorporate them within your project.

Connect with me on LinkedIn :- [Linkedin](https://www.linkedin.com/in/aryandev-shourie-175025229/)

Do check out my GitHub for amazing projects :- [Github](https://github.com/Aryan2727-debug)

View my Personal Portfolio :- [Aryan's Portfolio](https://aryan-s-portfolio.vercel.app/)