Web components
Web components are a set of web platform APIs that enable you to create custom, reusable HTML elements with encapsulated functionality. They provide a way to build component-based applications using native browser technologies, making them framework-agnostic and highly interoperable.
Key benefits
Web components offer several advantages for building modern web applications:
- Encapsulation: Styles and behaviour are scoped to the component, preventing CSS conflicts and ensuring predictable behaviour.
- Reusability: Components can be used across different frameworks and projects without modification.
- Standards-based: Built on native web technologies that are supported by all modern browsers.
- Performance: No framework overhead because they use direct browser APIs.
- Interoperability: Works seamlessly with React, Vue, Angular or vanilla JavaScript applications.
Real-world use cases
Web components are particularly useful for:
- Building design system components that work across multiple applications.
- Creating third-party widgets and embeddable content.
- Implementing micro-frontend architectures.
- Modernizing legacy systems by introducing new components gradually.
- Sharing components between teams using different frontend frameworks.
Core web component APIs
Web Components are built on four main web standards:
Custom elements
Define new HTML tags and their behaviour:
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = '<p>Hello World!</p>';
}
}
customElements.define('my-element', MyElement);
Shadow DOM
Provides encapsulation for DOM and styles:
class MyElement extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<style>p { color: red; }</style>
<p>This style won't leak out!</p>
`;
}
}
HTML templates
Define inert HTML that can be cloned and used:
<template id="my-template">
<style>
.card { border: 1px solid #ccc; }
</style>
<div class="card">
<slot name="content"></slot>
</div>
</template>
ES modules
Standard module system for loading components:
import './my-component.js';