Web Components — Explained with Examples
Web Components are reusable custom HTML elements built with browser-native APIs: Custom Elements, Shadow DOM, and HTML Templates.
Web Components consist of three browser APIs: Custom Elements (define new HTML elements with customElements.define()), Shadow DOM (encapsulated DOM and styles), and HTML Templates (<template> tags for reusable markup). Unlike framework components (React, Vue), Web Components are framework-agnostic — they work in any framework or no framework at all. Lit and Stencil are popular libraries that simplify Web Component development.
Think of Web Components like LEGO bricks. Each brick has a specific shape, connects via standard interfaces (the studs), and works with any other LEGO brick regardless of the set or theme. Similarly, Web Components are self-contained, interoperable, and can be mixed and matched across projects.
Web Components solve the framework fragmentation problem. A component built once with Web Component APIs can be used in React, Angular, Vue, or vanilla HTML.
// Define a custom element
class UserCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
static get observedAttributes() {
return ['name', 'avatar'];
}
attributeChangedCallback() {
this.render();
}
connectedCallback() {
this.render();
}
render() {
this.shadowRoot.innerHTML = `
<style>
.card {
border: 1px solid #ddd;
padding: 1rem;
border-radius: 8px;
display: flex;
align-items: center;
gap: 1rem;
}
img { width: 48px; height: 48px; border-radius: 50%; }
h3 { margin: 0; }
</style>
<div class="card">
<img src="${this.getAttribute('avatar') || 'default.png'}" alt="">
<h3>${this.getAttribute('name') || 'Unknown'}</h3>
<slot></slot>
</div>
`;
}
}
customElements.define('user-card', UserCard);<user-card name="Alice" avatar="alice.jpg">
<p>Frontend Developer</p>
</user-card>Web Components have broad browser support but lack features like declarative data binding or state management that frameworks provide. Libraries like Lit bridge this gap.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro