Web development has evolved significantly over the years, and one of the modern advancements is the introduction of web components. These components enable developers to create reusable and encapsulated HTML tags that can be used across different parts of a web application. In this article, we'll walk through a practical example of creating custom web components using HTML, CSS, and JavaScript.

Understanding the Basics

Web components consist of three main technologies:

  1. Custom Elements: Define new HTML elements.
  2. Shadow DOM: Encapsulate the internal structure of the component, ensuring it is isolated from the rest of the document.
  3. HTML Templates: Define chunks of markup that can be reused multiple times.

In our example, we'll create a simple webpage structure with a header, menu, main content area, and footer using custom elements.

HTML Structure

Here is the basic HTML structure of our webpage:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Web Component</title>
    <style>
    </style>
  </head>
  <body>
    <v-header>
      <v-menu></v-menu>
    </v-header>
    <v-main></v-main>
    <v-footer></v-footer>
    <script src="components.js"></script>
  </body>
</html>

JavaScript for Custom Components

Next, we define our custom components in components.js. Each component is a class extending HTMLElement, and we define its structure in the connectedCallback method, which is called when the element is added to the document.

document.addEventListener("DOMContentLoaded", () => {
  class VHeader extends HTMLElement {
    connectedCallback() {
      this.render();
    }
    render() {
      this.innerHTML = `
        <div class="center">
          <h1>THIS IS MY HEADER</h1>
          <v-menu></v-menu>
        </div>
      `;
    }
  }

  class VMenu extends HTMLElement {
    connectedCallback() {
      this.render();
    }
    render() {
      this.innerHTML = `
        <ul class="center">
          <li>Home</li>
          <li>About</li>
          <li>Contact</li>
          <li>Services</li>
        </ul>
      `;
    }
  }

  class VMain extends HTMLElement {
    connectedCallback() {
      this.render();
    }
    render() {
      this.innerHTML = `
        <div class="center">
          <h1>THIS IS MY MAIN</h1>
        </div>
      `;
    }
  }

  class VFooter extends HTMLElement {
    connectedCallback() {
      this.render();
    }
    render() {
      this.innerHTML = `
        <div class="center">
          <h1>THIS IS MY FOOTER</h1>
        </div>
      `;
    }
  }

  customElements.define("v-header", VHeader);
  customElements.define("v-footer", VFooter);
  customElements.define("v-main", VMain);
  customElements.define("v-menu", VMenu);
});

Explanation of the Code

Benefits of Using Custom Components