Understanding and using Web Components

February 3, 2022
htmlcomponent-based designweb components

Web Components are a set of web platform APIs that allow developers to create reusable and encapsulated custom elements for building web applications. They are part of the modern web standards and are natively supported by most major web browsers The primary goal of Web Components is to provide a standard way to create reusable components with encapsulated functionality that can be easily used and shared across different projects and frameworks. Web Components consist primarily of three main technologies, custom elements, the Shadow DOM, and HTML templates.


Custom Elements

Custom elements are the fundamental feature of Web Components that enables developers to define their own reusable and encapsulated HTML elements, these can be used to create self-contained components with their desired functionality and behavior, encapsulating both the structure and styling within their shadow DOM. Custom elements utilize the Custom Elements API, this API is used to define the elements and their behavior.


Shadow DOM

The Shadow DOM is a crucial part of Web Components that provides the encapsulation for custom elements. It allows developers to create a scoped DOM tree within a custom element, ensuring that the internal structure and styling of the component do not affect or get affected by the surrounding page. By creating a boundary between the main document's DOM and the shadow DOM, developers can prevent CSS styles and JavaScript from leaking into or interfering with the component's internals. This encapsulation is achieved by using the <shadow-root> element, which acts as the entry point for the shadow DOM inside the custom element. Within the shadow DOM, developers can define the component's internal structure and apply CSS styles that only affect the component's content. This allows for the creation of truly reusable and independent components, providing a powerful tool for building complex, maintainable, and modular web applications.


HTML Templates

HTML templates are a mechanism that allows developers to define inert chunks of markup in the HTML document. These templates serve as blueprints for custom elements, encapsulating the structure of the component without being immediately rendered on the page. They consist of two special tags, the template tag and the slot tag.

The <template> element is used to define these templates, and its content remains dormant until activated by JavaScript. By using templates, developers can create reusable components with complex structures and content that can be easily cloned and inserted into the DOM when needed. Templates are particularly useful when combined with JavaScript, allowing developers to dynamically instantiate and render components based on data and events.

The <slot> tag is used inside a Web Component's shadow DOM to define insertion points for content. It allows developers to project content from the host document into the shadow DOM, making it possible to customize the component's content from outside.


Web Component Example

As an example we’ll create a component that takes a string and renders a <div> tag with some basic styles set. When the Web Component is complete and registered with the browser we should be able to place it, it’ll look like this.

  
// Create a class that extends the HTMLElement
class MessageComponent extends HTMLElement {
    // Setup the constructor function and attach a Shadow DOM.
    constructor() {
        super();
        this.text = '';
        this.shadow = this.attachShadow({ mode: 'open' });
    }

    // observedAttributes() registers tag attributes for use in the component.
    static get observedAttributes() {
        return ['text'];
    }

    // attributeChangedCallback() handles changes to the attributes.
    attributeChangedCallback(property, oldValue, newValue) {
        if (oldValue === newValue) return;
        this[property] = newValue;
    }

    // connectedCallback() fires when the component is added
    connectedCallback() {
        // Create a <div>, style it a bit, append to shadow DOM.
        let div = document.createElement('div');
        div.style.fontWeight = 'bold';
        div.style.color = 'blue';
        div.innerText = this.text;

        this.shadow.appendChild(div);
    }
}


// Define the component with the Custom Elements API using the define() function.
customElements.define('message-component', MessageComponent);
  

The custom Web Component is now placeable using the name it was defined with. One thing to note, the final Web Component name is required to contain at least one dash character “-”. This prevents custom component names from colliding with any of the existing or future HTML standard tags.

  
<message-component text="Example message!"></message-component>
  

Web Components can be reusable and self-contained elements that enhance the modularity, maintainability, and scalability of web applications. These components can be shared with others easily and can be used across various frameworks and platforms. As a result, Web Components are an essential part of modern web development and complement other popular frontend frameworks like React, Angular, and Vue.js.