Cosa sono i Web Components

What are Web Components and how to use them

Discover what are Web Components, a tool to build UI elements independently from the Front End stack.

Reading time: 6'

38 likes
Published on January 12, 2022 (Updated on July 07, 2022)

In the previous article we talked about the new React framework called Remix and if you haven't had time to read it, I suggest you do it by clicking here. In case you fell in love with it and are thinking of migrating a project developed with Angular, for example, you will realize how long and tedious it would be to develop all the interface components already created. But don't worry because today's goal will be to understand what are Web Components and how they can help outsource the visual part of an application to be agnostic to the technology used in the Front End.

Our reading will start from understanding the needs to arrive at the final solution that will allow us to understand in detail what the Web Components are.

What are Web Components: the needs

There are several JavaScript frameworks or libraries that allow us to develop the logic and interface of an application. And very often within a company, especially if it is large, several technologies can coexist at the same time. This causes the duplication of some components that are used to build the UI, such as the following elements: buttons, inputs, tables, etc.

Consequently, if two incompatible technologies are adopted, to maintain the same style, the component code is rewritten, adapting it to the technology used. This results in:

  • waste of money and of time;
  • redundant maintenance of the code;
  • duplication of the development of new features.

Also, in case we want to change the technology of a platform, we will always have to rewrite the entire application if the code is not compatible.

These are the needs and therefore the problems that currently exist. Now let's try to understand in more detail the why to use the Web Components and so we will have a more general picture of what are the Web Components.

Why use Web Components?

The Web Components was born as solution to these problems, which are not a very recent technology and that they were discussed for the first time in 2011. Even if their first implementation is much more recent. This indicates immediately the need to have visual components that could be reused transversally from project to project.

To give a more concrete example, to develop a Button type element, having two applications built with two different technologies, we can use a Web Component and import it as if it were a normal HTML element. So we don't build a duplicate element for each technology but we outsource it, building our UI component library in a separate project.

From a small example, we can already evaluate the advantages we get from a Web Components library:

  • centralized management (new features, updates).
  • the components are reusable from project to project.
  • independence from the technology used.
  • single source of truth (in one place, we have all the components we need).

This underlines why to use the Web Components and how they are decisive for a cost saving and energy linked to the reusability of the visual elements of an application.

Now, having to answer the question what are the Web Components, we can state the following:

Web Components are reusable visual elements that do not depend on a specific technology

After the most boring part, that is the theory, let's move on to the development of a Web Component, and its integration within a project developed with NextJS.

How to implement the Web Components

Before we begin, I will introduce you to three fundamental concepts that will help us understand how Web Components work and which we will review in the example below:

  • customElements: the JavaScript API to build the component.
  • shadow dom: allows you to isolate the execution of the component (style, etc).
  • HTML templates: HTML API to show the element.

Moving on to the practice, I remind you that you can consult the final code on my project Github page here.

The goal is to create an HTML tag that can independently manage the typography style of our platform based on the component we want to show. Below is an example of its future use:

<web-typography component="h1" data-text="I am an h1 tag" /> <web-typography component="p" data-text="I am a paragraph" />

In this case, we can already see an advantage: we don't define the style because the Web Component itself will handle it. Let's see below how to create a Web Component that allows us to do this.

First I created a class, called * Typography *, which will handle the element of type text based on two main attributes:

  • component: defines the type of tag to show (h1, h2, h3, p, etc).
  • data-text: defines the textual content.

Finally, within the same class I define the style that each type of text element will have, so as to avoid the redundancy that I would get by adding the classes every time I go to create a tag individually.

// Create a class for the element class Typography extends HTMLElement { constructor() { // Always call super first in constructor super(); /* With mode === closed, you cannot access to the shadow dom from outside */ const shadow = this.attachShadow({ mode: 'closed' }); // Get tag type const tag = this.getAttribute('component') || 'span'; const wrapper = document.createElement(tag); // Take attribute content and put it inside the tag const text = this.getAttribute('data-text'); wrapper.textContent = text; // Create some CSS to apply to the shadow dom const style = document.createElement('style'); style.textContent = ` h1 { font-size: 3rem; font-weight: 700; } h2 { font-size: 2rem; font-weight: 600; } p { font-size: 1.2rem; font-weight: 400; } `; // Attach the created elements to the shadow dom shadow.appendChild(style); shadow.appendChild(wrapper); } } // Define the new element (name must contain hyphens) customElements.define('web-typography', Typography);

The constructor function will be invoked as soon as the HTML component is rendered. Inside we access the attributes, define the style and finally insert the elements created to the assigned DOM, the shadowDom. The latter is an isolated DOM that we can access or not, based on the mode parameter.

Once the basic behavior has been defined, we use the customElements API present in most browsers to define a Web Component and thus make it possible to use it as a normal HTML tag.

We have just seen the basic concepts of a Web Component and we just have to use it.

In the next example I integrated a Web Component into an application built with NextJS, which then uses ReactJS.

First we need to import the JS file:

useEffect(() => import('../components/Typography/index.js'), []);

Here I used the useEffect, since it is an application in ReactJS, and I used the dynamic import, to avoid putting the component inside the public folder of NextJS. In another article we will see how to use Web Components as JSX tags by importing and using them directly. So, stay tuned!

Then we move on to the actual use of our component which will be shown as any HTML tag with the style we have defined inside it:

<web-typography data-text="I am a Web Component" component="h1" />

We can also use this component in an application written with Angular, VueJS or in pure JavaScript.

The result will be the following:

What are Web Components - Example

Browser compatibility

Most browsers currently support Web Components. To check the compatibility matrix you can refer to this link. If you want to support a browser that is not natively compatible with the Web Components, you can always install a polyfill following the procedure described here.

Unfortunately, for the moment, we have finished our journey which has made us understand what are Web Components. In a later article we will talk about how to use them as simple ES6 imports, and I will introduce you to the StencilJS library. This is a very powerful tool for creating Web Components. If you want to get ahead of the times, I suggest you take a look at the documentation on the [official page] (https://stenciljs.com/).

Now it is time to hear your voice. If you liked this article and you want to support me, just follow these simple, easy and free steps:

  1. Leave a like by clicking on the heart icon below.
  2. Share this post on your social accounts or with your friends.
  3. Follow me on Instagram, Facebook, Twitter and on Github.
  4. Subscribe to the newsletter below to not miss any articles, discounts or gossip (there will be many).

Thank you so much for your attention and have a nice day!

Articles related to JavaScript

Courses of JavaScript

  • Masterclass19% off
    Max 6 students
    Masterclass JavaScript

    Building a scalable app with NextJS and GraphQL

    NextJS, Graphql, Tailwind and Strapi. The most important technologies in a single masterclass.

    • JavaScript
    • NextJS
    More info
  • Masterclass
    Max 10 students
    React masterclass

    Build your portfolio with ReactJS and Typescript

    Master ReactJS and Typescript by building your own portfolio with NextJS in only 12.5 hours.

    • JavaScript
    • NextJS
    More info

Newsletter

Subscribe to the newsletter to receive updates about programming news, course discounts, and other content published on the platform.
You will get instantly a 10% discount.