Table of contents
1.
Introduction
2.
What are web components?
3.
How to implement web components?
3.1.
A custom element example
3.1.1.
HTML
3.1.2.
JS
3.2.
The shadow DOM example
3.2.1.
HTML
3.2.2.
JS
3.3.
HTML template example
3.3.1.
HTML
3.3.2.
JS
4.
Will the web components replace React?
5.
Frequently Asked Questions (FAQs)
6.
Key Takeaways
Last Updated: Mar 27, 2024

Web Components

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We all are familiar that react has a very high code reusability aspect. We can build and reuse almost everything in react.

Web components are getting very popular because of the availability of reusable code components which can be embedded directly into our react application. Definitely, web components are here to stay for long. As we speak, the support for web components is growing. More and more resources, libraries and tools are becoming available for developers who are interested in using web components.

Also, there is an interesting discussion about how web components will replace the modern frontend libraries. So in this article, we will also see the difference between web components and React.

Let us dive deep into the concept of web components and learn how are they used in react.

What are web components?

The web components are a way of building custom, reusable, encapsulated HTML tags to use in web pages and web apps.

The web components in react are based on the existing web standards available to us in the browsers. And, also these web components can also be used in combination with any javascript library or framework that works with the HTML. 

This implies that web components are framework agnostic.

The components built on The Web Component standard are supported by mostly all of the major browsers.

source: webcomponents.org

When a web component is built, it can be published into an online registry such as Docfire, so that the other developers can utilise these web components in their projects.

We can find many of the web components which are already made and are ready to use on the  Web Components’ official webpage.

How to implement web components?

Below given are some of the different ways in which we can implement web components in our application.

  • A custom element is a method of defining an HTML element by using the browser’s API. The custom component has its own semantic tag and methods, like the one in the React component.
  • The shadow DOM is a way to isolate the DOM elements and the scope of CSS locally to prevent breaking of changes and from affecting the other elements.
  • The HTML template is a way of writing invisible HTML, which will act as a template that we can use to operate the javascript’s query selector method.

Let us learn more about how these methods of implementation work, along with the code examples.

A custom element example

The web component’s custom elements are made using the browser’s javascript API. The custom element is defined using the class keyword in javascript that extends the HTMLElement. Once it is defined, the custom element can be used as many times as you need. 

HTML

<button-component></button-component>
<button-component></button-component>
<button-component></button-component>

JS

class ButtonComponent extends HTMLElement {
 connectedCallback() {
   this.innerHTML = `<button>Click on me!</button>`;
 }
}

customElements.define('button-component', ButtonComponent);
You can also try this code with Online Javascript Compiler
Run Code

Output

A custom element name must include a dash or the browser will complain that you have an invalid element name. You need to name a button as <primary-button> or <button-component> instead of just <button>.

Custom elements also have lifecycle callbacks for running code during specific times of its existence. These lifecycle callbacks work in a similar way to React's lifecycle methods.

As of today, you need to write custom elements.

The shadow DOM example

Shadow DOM allows you to write HTML elements that were scoped from the actual DOM tree. It’s attached to the parent element, but won’t be considered as its child element by the browser. Here is an example:

HTML

<div id="example"></div>
<button id='button-component'>This button doesn't turn yellow</button>

JS

const shadowRoot = document.getElementById('example').attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `<style>
button {
 background: yellow;
}
</style>
<button id="shadow-button"> This is shadow button</button>`;
You can also try this code with Online Javascript Compiler
Run Code

Any code that is written inside the shadow DOM will be encapsulated by the code outside it. The benefit of using the shadow DOM is that any CSS code written by us will be local, and it will not affect any element outside it.

When we inspect the shadow element, we can see that it is marked with the #shadow-root.

When we try to select the shadow button with document.getElementById(‘shadow-button’), the browser will return the null value. We need to select the parent element and then grab its shadowRoot object first.

const elem = document.getElementById('example').shadowRoot
elem.getElementById('shadow-button')
You can also try this code with Online Javascript Compiler
Run Code

HTML template example

The HTML template allows us to write invisible HTML elements which we can iterate over with javascript in order to display the dynamic data. To write a HTML template, we need to wrap the elements inside a <template> tag.

HTML

<template id="people-template">
 <li>
   <span class="name"></span> &mdash;
   <span class="age"></span>
 </li>
</template>
<ul id="people"></ul>

Then you can iterate through the template above with a JavaScript selector and append it into the <ul> element.

JS

const fragment = document.getElementById('people-template');
const people = [
{ name: 'Daniel', age: 22 },
{ name: 'Jessie', age: 29 },
{ name: 'Andy', age: 32 }
];
people.forEach(person => {
const instance = document.importNode(fragment.content, true);

instance.querySelector('.name').innerHTML = person.name;
instance.querySelector('.age').innerHTML = person.age;

document.getElementById('people').appendChild(instance);
});

When we use the template, we can fetch data from the API server and then use the template to return the data in a well-defined structured way.

Output

Now we know how the web components work.

Will the web components replace React?

The web components are a set of different technologies that are used together in the code to involve reusable elements which are encapsulated from the rest of the code. On the other hand, React is a famous javascript library that is meant to help us write the user interface in a declarative way. 

The modern front-end development approach requires many other things besides the components. That is why we do not have to be afraid to use React and it is an ecosystem of tools and libraries. It is a surety that it would not be able to be replaced by the web components any sooner.

Also Read, Front End Web Development

Frequently Asked Questions (FAQs)

1. What are web components in react?
The web Components are a way of building custom, reusable, encapsulated HTML tags to use in web pages and web apps.

2. What is the need for web components?
The web components are a set of different technologies that are used together in the code to involve reusable elements which are encapsulated from the rest of the code.

Key Takeaways

We learned about the concept of web components in react. This is an advanced concept of web components in React that allows us to use custom-made web components in our UI. We also learned about the implementation of web components in react.

Apart from this, you can also expand your knowledge by referring to these articles on Javascript and React.
Check out this problem - No of Spanning Trees in a Graph

For more information about the react framework for frontend development, get into the entire Frontend web development course.

Happy Learning!
 

Live masterclass