Open In App

ReactJS Web Components

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Web components, encapsulated HTML tags for web development, are versatile, framework-agnostic elements native to HTML, usable seamlessly in various environments like React and Angular.

What are the types of web components?

There are three types of web components:

1. Custom Elements:

Steps to create a Custom Element:

  • Create a class that extends HTMLElement using the class syntax
  • Register the element using window.customElements.define() method.

Lifecycle methods for Custom Elements:

  • constructor(): This callback method is called when an instance of the element is created or upgraded
  • connectedCallback(): This callback method is called every time when the element is inserted into the DOM
  • disconnectedCallback(): This callback method is called every time the element is removed from the DOM.
  • adoptedCallback(): This callback method is called whenever the custom element is moved to a new document.
  • attributeChangedCallback(attributeName, oldValue, newValue): Called when an attribute is added, removed, updated, or replaced by methods that are available to us so we have a constructor.

Example 1: In this example, we created a custom element with the tag <test-element>.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Web Components</title>
</head>
 
<body>
    <div>
        <h1>Custom Element</h1>
        <test-element></test-element>
    </div>
 
    <script type="text/javascript">
        class TestElement extends HTMLElement {
            constructor() {
                super();
 
                // Setting an attribute
                this.setAttribute('name', 'Marry');
            }
            connectedCallback() {
                this.innerHTML =
                    `<div>
                        <p>Hello ${this.getAttribute('name')}!</p>
                        <p>how are you</p>
                    </div>`
            }
        }
         
        // Register the custom element
        customElements.define('test-element', TestElement);
    </script>
</body>
 
</html>


Output:

Output

2. Shadow DOM: 

  • Used for self-contained components.
  • Contains style and markup of the component.
  • Creates a “shadowRoot” which can be referenced later when needed.
  • Attachable to an element using element.attachShadow({mode: open }).
  • document.querySelector() method doesn’t work for the nodes in ShadowDOM 

Example 2: In this example, we created a shadow DOM and attached it to our custom element.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Web Components</title>
</head>
 
<body>
    <div>
        <h1>Shadow DOM </h1>
        <test-element></test-element>
    </div>
 
    <script type="text/javascript">
        class TestElement extends HTMLElement {
            constructor() {
                super();
 
                // Setting an attribute
                this.setAttribute('name', 'ashton');
 
                // Attaches a shadow DOM tree to
                // <test-element> and returns a reference
                const shadowRoot =
                    this.attachShadow({ mode: 'open' });
            }
 
            connectedCallback() {
                this.shadowRoot.innerHTML =
                    `<style>
                            div {
                                background:cyan;
                            }
                        </style>
                        <div>
                            <p>Hello ${this.getAttribute("name")}!</p>
                            <p>Nice to meet you</p>
                        </div>`;
            }
        }
 
        // Register the custom element
        customElements.define('test-element', TestElement);
    </script>
</body>
 
</html>


Output:

Output

HTML Templates:

  • Templates can contain both HTML and CSS.
  • Templates can be defined in the document using the <template> tag.
  • They are used to define markup structures.
  • The <template> element is not rendered on the page until we attach it to the DOM using JavaScript.

Example 3: In this example, we created a custom template to show the data of the students.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Web Components</title>
</head>
 
<body>
    <div>
        <h1>HTML Templates</h1>
        <template id="student_template">
            <style>
                li {
                    color: red;
                    list-style: none;
                }
            </style>
            <li>
                <span class="name"></span> —
                <span class="score"></span>
            </li>
        </template>
        <test-element></test-element>
        <ul id="students"></ul>
    </div>
 
    <script type="text/javascript">
        class TestElement extends HTMLElement {
            constructor() {
                super()
                const shadowRoot =
                    this.attachShadow({ mode: "open" });
 
            }
            connectedCallback() {
                let students = [
                    { name: "Emma", score: 94 },
                    { name: "Ashton", score: 72 },
                    { name: "Hannah", score: 86 },
                    { name: "Steve", score: 90 },
                    { name: "Amy", score: 75 },
                ]
 
                students.forEach(student => {
                    let template =
                        document.getElementById("student_template");
                    let templateContent =
                        template.content.cloneNode(true);
 
                    // Append a clone of the template
                    // content to the shadow root
                    this.shadowRoot.appendChild(templateContent);
 
                    this.shadowRoot.querySelector('.name')
                        .innerHTML = student.name // Add the name
                    this.shadowRoot.querySelector('.score')
                        .innerHTML = student.score // Add the score
 
                    // Append the list to the ul students
                    document.getElementById("students")
                        .appendChild(this.shadowRoot)
                })
            }
        }
         
        // Register the custom element
        customElements.define('test-element', TestElement);
    </script>
</body>
 
</html>


Output:

Output

Third-Party Web Available Components:

  • Material Web Components: The material web components are the Web Component version of the Material UI framework which is designed and developed by Google. 
  • Bootstrap in Web Components: Bootstrap is an awesome CSS framework that lets you develop a beautiful and responsive website in no time using its pre-styled component. If you want to use Bootstrap in your ShadowDom-based web component, You have to include the bootstrap CSS in each component. This can be done simply by using a <link> tag referring to the Bootstrap CSS in your ShadowDOM.
  • Elix: Elix is an open source of ready-to-use web components for common UI patterns, such as carousels, buttons, menus, etc. You can also customize the web components provided by ELix or even build your own custom web components which extend the already implemented Elix components.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads