Master Web Components: Create and Host Your Own
Tags: webdev, javascript, react, typescript
Published: 2024-05-17 11:24:47

In modern web development, creating reusable and embeddable web components is crucial for maintaining scalable and maintainable codebases. In this blog post, we'll walk you through the process of creating a reusable CreditsComponent using HTML, CSS, and JavaScript. By the end of this tutorial, you'll know how to build, customize, and host your own web components for free.

The other day, I was developing a project. After completing that project, I had to add credits manually. At that time, I thought about how we can make a reusable component in HTML, CSS, and JS. After some research, I came to know that we can achieve this by leveraging the power of class extension in JS and CDNs. So lets learn how we can create reusable web components and host them with ease.

## 1. What are Web Components?

Web components are a set of web platform APIs that allow you to create new, reusable, and encapsulated HTML tags to use in web pages and web apps. They consist of three main technologies:

1. **Custom Elements:** Define new HTML elements.
2. **Shadow DOM:** Encapsulate styles and markup.
3. **HTML Templates:** Define reusable HTML fragments.

## 2. Setting Up the Environment.
Before we begin, ensure you have a text editor (like VSCode) and a basic understanding of HTML, CSS, and JavaScript. Additionally, use a modern browser that supports web components. (Most of popular browsers supports this feature).

![Master Web Components: Create and Host Your Own](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cikedpudpmdojbxusbz9.PNG)

## 3. Creating the `CreditsComponent`
We'll start by defining a class for our custom element and setting up its Shadow DOM.

### Step 1: Define the class and constructor

```
# credit-component.js
class CreditsComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
```
Create a new credit-component.js file. Here, we extend HTMLElement to create a custom element and use the constructor to initialize the component. (You don't need to fully understand this code. Just copy and paste).

### Step 2: Attaching the Shadow DOM
```
this.attachShadow({ mode: "open" });
```
The Shadow DOM provides encapsulation, ensuring styles and markup within the component don’t affect the rest of the page.

### Step 3: Adding Styles

```
const style = document.createElement("style");
style.textContent = `
  .Credits {
    min-height: 10vh;
    box-shadow: 10px 10px 30px black;
    background-color: white;
    border-radius: 50px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    justify-content: space-between;
    margin: 2rem 4rem;
  }
  .links {
    display: flex;
  }
  .links > a {
    text-decoration: none;
    color: black;
    font-size: 20px;
    margin: 0 4.5px;
  }
`;
this.shadowRoot.append(style);
```

This CSS styles the component, ensuring it looks consistent regardless of where it’s used, and appends it to shadow DOM.

### Step 4: Creating the HTML Template

```
const container = document.createElement("div");
container.classList.add("Credits");
container.innerHTML = `
  <h1>Made by GrowWithTalha 💜</h1>
  <div class="links">
    <a href="https://growwithtalha.vercel.app/">Portfolio</a>
    <a href="https://github.com/GrowWidTalha">Github</a>
    <a href="https://www.linkedin.com/in/growwithtalha-webdeveloper">Linkedin</a>
    <a href="https://twitter.com/GrowWithTalha">Twitter</a>
    <a href="mailto:growwithtalha@outlook.com">Contact</a>
  </div>
`;
this.shadowRoot.append(container);
```
This creates a simple HTML structure within the component. You can always change the styles and HTML structure according to your needs.

### 4. Adding Dynamic Content with Attributes
To make our component more flexible, we'll use the connectedCallback method to handle dynamic content.

```
connectedCallback() {
  const credits = this.getAttribute("credits") || "";
  const creditsArray = credits.split(",");
  const creditsList = this.shadowRoot.querySelector(".Credits .links");

  creditsArray.forEach((credit) => {
    const listItem = document.createElement("a");
    listItem.href = "#";
    listItem.textContent = credit.trim();
    creditsList.appendChild(listItem);
  });
}
```

This method allows the component to accept a credits attribute and dynamically add links based on its value.

### 5. Registering the Custom Element
Finally, we need to register our custom element.
```
customElements.define("credits-component", CreditsComponent);
```
This makes our component available for use in any HTML document.

### 6. Using the CreditsComponent in Your Project
To use the CreditsComponent, simply link the credit-component.js file in your HTML document and include this in your HTML:

```
<credits-component credits="Blog, Tutorials, Contact"></credits-component>
```
This will render the component with additional dynamic links.
NOTE: The credits attribute is totally optional and you don't have to add them.

#### Full code for `credits-component.js`
```
class CreditsComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });

    // Styles
    const style = document.createElement("style");
    style.textContent = `
      .Credits {
        min-height: 10vh;
        box-shadow: 10px 10px 30px black;
        background-color: white;
        border-radius: 50px;
        display: flex;
        align-items: center;
        padding: 0 20px;
        justify-content: space-between;
        margin: 2rem 4rem;
      }
      .links {
        display: flex;
      }
      .links > a {
        text-decoration: none;
        color: black;
        font-size: 20px;
        margin: 0 4.5px;
      }
    `;

    // HTML Template
    const container = document.createElement("div");
    container.classList.add("Credits");
    container.innerHTML = `
      <h1>Made by GrowWithTalha 💜</h1>
      <div class="links">
        <a href="https://growwithtalha.vercel.app/">Portfolio</a>
        <a href="https://github.com/GrowWidTalha">Github</a>
        <a href="https://www.linkedin.com/in/growwithtalha-webdeveloper">Linkedin</a>
        <a href="https://twitter.com/GrowWithTalha">Twitter</a>
        <a href="mailto:growwithtalha@outlook.com">Contact</a>
      </div>
    `;

    // Append styles and container to the shadow DOM
    this.shadowRoot.append(style, container);
  }

  connectedCallback() {
    const credits = this.getAttribute("credits") || "";
    const creditsArray = credits.split(",");
    const creditsList = this.shadowRoot.querySelector(".Credits .links");

    creditsArray.forEach((credit) => {
      const listItem = document.createElement("a");
      listItem.href = "#";
      listItem.textContent = credit.trim();
      creditsList.appendChild(listItem);
    });
  }
}

customElements.define("credits-component", CreditsComponent);
```

Now we have our component setup locally. But thats not a convenient option. Now we have to host this `credit-component.js` file as a CDN so we can easily link it in our HTML page and use it.

## 7. Hosting Your Web Component
In order to host our web component we have to push our code to github and create a jsdelivr link to access it.

### Step 1. Push `credits-component.js` to Github.
First step is to push your code on github. If you don't know how to do it then just go and learn. It will only take you couple of minutes to learn.

### Step 2. Create a JSDelivr link:

The next step is to create a cdn link. Don't its free and you don't even have to create any account.
```
https://cdn.jsdelivr.net/gh/<YourUserName>/<repo-name>@master/<File-Name>
```

- **YourUserName**: Replace this part with your Github user name.
- **repo-name**: Replace this with your repo name.
- **file-name**: Replace this part with your file name with .js extension.

After completing the above steps your URL should look like this.
```
https://cdn.jsdelivr.net/gh/GrowWidTalha/credit-component-cdn@master/credit-component.js
```
If you paste this URL in a browser you will get the contents of your credit-components.js file. Congrats you just created your first CDN.

Now use this link in your HTML documents to use your custom component.

```
<-- Your Other HTML code.....--!>
<credit-component></credit-component>

<script src="Your CDN link"></script>
<-- Your Other HTML code.....--!>
```

And voila you made a custom web component and hosted it on a CDN.

## Conclusion
Building reusable web components streamlines development and improves code maintainability. You've learned to create a custom CreditsComponent using HTML, CSS, and JavaScript, enhancing modularity and flexibility in your projects. You also learned to HOST these components on the web. Experiment with customization to suit your needs and enjoy the benefits of simplified coding. Till then Keep Growing.