DEV Community

Yvan Guekeng Tindo
Yvan Guekeng Tindo

Posted on • Edited on • Originally published at gtindo.dev

2 1

How to Build a Simple Web Component from Scratch

Web components are a set of powerful tools that allow you to create your own custom HTML elements. These elements can be used just like any other HTML tag (e.g., <div>, <span>) but with your own special behavior and design.

The core technologies behind web components are:

  • Custom Elements: Allows you to define new HTML tags.
  • Shadow DOM: Keeps your element’s structure and styles isolated from the rest of the page.
  • HTML Templates: Lets you define reusable HTML that isn’t rendered until you use it.

In this guide, we'll build a simple counter component from scratch. This counter will have buttons to increase and decrease a number.

The component will look like this:

Image description

Here is the link for final version with all the source code.


Prerequisites

Before we begin, here’s what you need to know:

  • Basic JavaScript.
  • A simple understanding of how the DOM (Document Object Model) works (don’t worry if you’re not an expert — we’ll cover what you need).

Setting Up the Project

First, let’s set up a simple project with two files:

  1. counter.html: The HTML file that will hold the page structure.
  2. counter.js: The JavaScript file where we define our custom counter element.

counter.html

This file contains the basic HTML structure of your page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Counter Component</title>
    <script src="./counter.js"></script>
  </head>
  <body>
    <!-- The counter component will be inserted here -->
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Creating the Template

A template is just a way to define the structure of our custom element (like what it looks like). Let’s create one for our counter:

counter.html (Add the Template)

<body>
  <template id="x-counter">
    <div>
      <button id="min-btn">-</button>
      <span id="counter-display">0</span>
      <button id="plus-btn">+</button>
    </div>
  </template>
</body>
Enter fullscreen mode Exit fullscreen mode

Here’s what each part of this template does:

  • <button id="min-btn">-</button>: A button to decrease the counter.
  • <span id="counter-display">0</span>: A place to show the current counter value.
  • <button id="plus-btn">+</button>: A button to increase the counter.

This template will not show up on the page directly. We will use it later to create our custom element.


Defining the Custom Counter Element

Now, we’ll write the JavaScript to define how our counter works. We’ll create a class that extends the basic HTMLElement, which is what all HTML elements are built on.

counter.js

class XCounter extends HTMLElement {
  constructor() {
    super();
    this.counter = 0; // Start the counter at 0
    this.elements = {}; // To store references to our buttons and display
  }

  connectedCallback() {
    // This runs when the element is added to the page
    const template = document.getElementById("x-counter");
    this.attachShadow({ mode: "open" });

    // Clone the template and add it to our custom element's shadow DOM
    this.shadowRoot.appendChild(template.content.cloneNode(true));

    // Get references to the buttons and display
    this.elements = {
      plusBtn: this.shadowRoot.querySelector("#plus-btn"),
      minBtn: this.shadowRoot.querySelector("#min-btn"),
      counterDisplay: this.shadowRoot.querySelector("#counter-display")
    };

    // Show the initial counter value
    this.displayCount();

    // Add event listeners for the buttons
    this.elements.plusBtn.onclick = () => this.increment();
    this.elements.minBtn.onclick = () => this.decrement();
  }

  increment() {
    this.counter += 1;
    this.displayCount();
  }

  decrement() {
    this.counter -= 1;
    this.displayCount();
  }

  displayCount() {
    this.elements.counterDisplay.textContent = this.counter;
  }
}

// Register the custom element so we can use it in HTML
customElements.define("x-counter", XCounter);
Enter fullscreen mode Exit fullscreen mode

Breaking it Down:

  1. The constructor: This is where we set up initial values for our counter and store references to the elements inside the counter.

  2. connectedCallback: This function runs when the custom element is added to the page. Here, we:

    • Attach a shadow DOM to keep our element’s structure and styles separate from the rest of the page.
    • Clone the template we created earlier and add it to the shadow DOM.
    • Set up references to the plus and minus buttons and the display where the counter is shown.
  3. increment and decrement: These functions change the value of the counter by 1 and update the display.

  4. displayCount: This function updates the text inside the <span> to show the current counter value.

  5. Register the element: Finally, we tell the browser to recognize <x-counter> as a custom element that uses the XCounter class.


Using the Counter Component

Now that our counter is defined, we can use it just like any other HTML element. Here’s how to add it to the page:

counter.html (Add the Custom Element)

<body>
  <x-counter></x-counter>

  <template id="x-counter">
   ...
  </template>
</body>
Enter fullscreen mode Exit fullscreen mode

This will create a counter on the page with two buttons — one to increase and one to decrease the number. The counter will start at 0, and you can interact with it by clicking the buttons.


Style the element

Styling can be done in a few ways, but when using the Shadow DOM, we can encapsulate the styles to ensure they don’t interfere with other parts of the page. In this section, we will style our counter element using adopteStyleSheet.

counter.js with Styling

...
    connectedCallback() {
        ...
         this.attachShadow({ mode: 'open' });

         // Add styles to the component
         const sheet = new CSSStyleSheet();
         sheet.replaceSync(this.styles());
         this.shadowRoot.adoptedStyleSheets = [sheet];

         // Clone the template and add it to our custom element's shadow DOM
       this.shadowRoot.appendChild(template.content.cloneNode(true));
        ...
    }
    ...
    styles() {
      return `
         :host {
          display: block;
          border: dotted 3px #333;
          width: fit-content;
          height: fit-content;
          padding: 15px;
        }

        button {
          border: solid 1px #333;
          padding: 10px;
          min-width: 35px;
          background: #333;
          color: #fff;
          cursor: pointer;
        }

        button:hover {
          background: #222;
        }

        span {
          display: inline-block;
          padding: 10px;
          width: 50px;
          text-align: center;
        }
      `
    }
    ...
...
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we learned how to create a simple web component:

  • We used an HTML template to define the structure of our custom element.
  • We added shadow DOM to isolate the styles and behavior of our component.
  • We wrote JavaScript to control the logic of the counter (increment, decrement, and display the count).

Web components are a great way to make your web applications more modular and reusable.

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay