What is Web Components?
TL;DR
Browser-native custom elements API enabling reusable, encapsulated HTML components.
Web Components are a set of web platform APIs that allow you to create custom, reusable, encapsulated HTML tags for use in web pages and web apps. While Frontend Accelerator primarily uses React components, understanding Web Components helps when integrating third-party widgets or building framework-agnostic libraries.
Core technologies:
- Custom elements: Define new HTML tags
- Shadow DOM: Encapsulated styling and markup
- HTML templates: Reusable markup fragments
- ES modules: Standard module imports
Creating a custom element:
class UserCard extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<div class="user-card">
<h3>${this.getAttribute('name')}</h3>
<p>${this.getAttribute('email')}</p>
</div>
`;
}
}
customElements.define('user-card', UserCard);
// Usage:
<user-card name="John Doe" email="john@example.com"></user-card>
Using in React:
declare global {
namespace JSX {
interface IntrinsicElements {
'user-card': { name: string; email: string };
}
}
}
export function Profile() {
return <user-card name="Jane" email="jane@example.com" />;
}
Key benefits:
- Framework Agnostic: Works everywhere
- Encapsulation: Isolated styles and behavior
- Reusability: Share across projects
- Browser native: No build step needed
AI-friendly: Web Components follow standard web APIs. AI tools understand the custom element lifecycle, shadow DOM patterns, and how to bridge Web Components with React, making it easy to integrate third-party components or build framework-independent solutions.