Introduction to Web Components and How to Start Using Them
Bring some harmony to your organization's component library: here's our guide to web components and how to start defining your own.
Feb 3rd, 2024 6:00am by
Photo by Blaz Erzetic on Unsplash
.circle
{
height: 150px;
width: 150px;
border: solid 1px;
border-radius: 50%;
display: inline-block;
}
<span class="circle"/>
<div class="w-20 h-20 rounded-full border-2
border-black flex justify-center
items-center">
Tailwind is a nice framework. However, I then have to effectively continue using that library for everything else. And there is little guarantee how well these would work across browsers. Plus, like its predecessor Bootstrap, Tailwind is subject to the whims of fate. What we really want is an “official” way to express a component.
Enter Web Components
A web component is a way to “create an encapsulated, single-responsibility code block that can be reused on any page”. They are made of existing standards expressed as Web APIs, that vendors have been agreeing with and implementing over the years. They have enough use and maturity by now to challenge the existing popular frameworks. All modern browsers have supported the spec for some time. Web Components allow you to define custom elements (for example “my-circle”) and then register them. That’s great, but as I hinted, controlling these requires control of CSS everywhere else. To address this, a web component can contain its own set of rules in a shadow DOM. This is just a separate object tree that won’t clash with the main one. Finally, templates and slots allow you to define inert fragments that are not displayed when rendered but can later be re-used. So I can define this:
<template id="my-paragraph">
<p>My paragraph</p>
</template>
How to Define Your Own Web Components
Web components are custom HTML elements such as <my-circle />. The name must contain a dash so that it never clashes with elements officially supported in the HTML specification. So we already start with a relationship: the browser will always know HTML tags but will respect new ones. How do they know about the new ones?
After defining the components as a class, you register it with the CustomElementRegistry, like so:
customElements.define( 'my-circle', MyCircle );
class MyCicrle extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
// Create spans
const wrapper = document.createElement("span");
wrapper.setAttribute("class", "smallcircle");
// Create some CSS to apply to the shadow dom
const style = document.createElement("style");
console.log(style.isConnected);
style.textContent = `
.smallcircle {
height: 150px;
width: 150px;
border: solid 1px;
border-radius: 50%;
display: inline-block;
color: #ffffff;
}
`;
// Attach the created elements to the shadow dom
shadow.appendChild(style);
console.log(style.isConnected);
shadow.appendChild(wrapper);
}
}
There is no doubt that the cleanliness of defining a custom element does make using web components on the page a nice process. And the code change is straightforward enough:
...
let clr;
if (this.hasAttribute("color"))
{
clr = this.getAttribute("color");
}
else
{
clr = "white";
}
style.textContent = `
.smallcircle {
height: 150px;
width: 150px;
border: solid 1px;
border-radius: 50%;
display: inline-block;
color: ${clr};
}
`;
...
Web Components in the Wild
But have web components arrived too late to push out the popular frameworks? In most cases, web components can work next to framework components, though a separate issue about server-side rendering is definitely a fly in the ointment (which I won’t go into here). The strength of web components really arrives when a small UX team wants to develop a library that they know will survive the test of time. Ideas crossing between the business and development team no longer have to be translated into Angular or React. Complex components that match a brand identity can be used like a normal tag. Instead of a “my-circle” tag, think of a “my-company-header” tag that can be used throughout an organization — the UX team controls development but without the risk of framework lock-in. This brings designers and builders much closer together. So with web components, an organization’s component library is not only more stable and less dependent on another layer defined elsewhere, but the language they use will be much more explicable beyond the development team. It brings a little bit of harmony to the Wild West of the web.
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don't miss an episode. Subscribe to our YouTube
channel to stream all our podcasts, interviews, demos, and more.