UI-Library

Logo

Everything ever learned in the UI space

View the Project on GitHub akhilarjun/UI-Library

Web Components

Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

It consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

How to create a Custom Element?

Demo

Demo of Web Elements

CustomElementRegistry API

Create a class which extends the normal HTMLElement and add extra functionality as required.

Make sure to call the super() method in the constructor

class HelloWorld extends HTMLElement {
  constructor() {
    super(); // <-- Very Important
    this.innerHTML = "Hello World";
  }
}

Once the class is complete, register it using the CustomElementRegistry implementation customElements.define() method like this

customElements.define("hello-world", HelloWorld);

Here, hello-world is the DOM string that will be used in the HTML files to re-use this component

LifeCycle Hooks

  1. connectedCallback - This lifecycle hook is called once the component is attached to the DOM. This will be after initialization of the component.
  2. disconnectedCallback - This lifecycle hook will be called after the component is removed from the DOM
  3. attributeChangedCallback - This lifecycle hook will be called whenever the observed attributes of the component changes.

Observed Attributes will be returned from the static method of observedAttributes.

example:

connectedCallback() {
    console.log("Hello World Attached to DOM");
}

disconnectedCallback() {
    console.log("Hello World Removed from DOM");
}

static get observedAttributes() {
    return ["NAME_OF_ATTRIBUTE_HERE"];
}

attributeChangedCallback(prop, oldValue, newValue) {
    console.log("Attribute changed");
}

Shadow DOM

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal DOM.

Shadow Dom Explanation

Shadow DOM can be attached to the component using

let shadow = elementRef.attachShadow({ mode: "open" });

There are two modes in the Shadow DOM method of attachShadow namely open and closed

Shadow DOM with open mode can be accessed via the main application context. And can be used to alter its structure, style or functionality

let myShadowDom = myCustomElem.shadowRoot;

Shadow DOM with closed mode cannot be accessed outside the custom element context.

let myShadowDom = myCustomElem.shadowRoot; // <-- This will return null