Web components
What are web components?
Web components are a set of native browser standards for creating reusable, self-contained HTML elements. A developer defines a new tag, such as <product-card>, with its own markup, styles and logic, then uses it on any page like a built-in element.
Because they are part of the platform, web components need no framework and work in every modern browser. They are a common way to share interface pieces between projects and between teams that use different technologies.
The three standards behind web components
- Custom elements: define new HTML tags and their lifecycle.
- Shadow DOM: encapsulates markup and CSS so styles do not leak in or out.
- HTML templates: declare inert markup with
<template>and<slot>that is cloned when needed.
How to create a custom element
class HelloCard extends HTMLElement {
connectedCallback() {
const root = this.attachShadow({ mode: 'open' });
root.innerHTML = `<p>Hello, ${this.getAttribute('name')}</p>`;
}
}
customElements.define('hello-card', HelloCard);The element is then used in HTML with <hello-card name="Alex"></hello-card>. The browser runs the class code whenever the tag appears in the page.
Web components vs framework components
| Criteria | Web components | Framework components |
|---|---|---|
| Runtime | Native browser APIs | Framework library |
| Portability | Works in any stack | Tied to one framework |
| Style isolation | Built in with Shadow DOM | Depends on the tooling |
| State and rendering | Manual or via a small helper library | Provided by the framework |
Best practices and pitfalls
- Use them for shared, framework-independent interface pieces such as buttons, cards or widgets.
- Expose customization through attributes, slots and CSS custom properties.
- Keep meaningful content in the light DOM when it matters for search engines, since content in the shadow DOM may be harder to index.
- Follow accessibility basics: roles, labels and keyboard support are not automatic.
- Consider a light helper library such as Lit to reduce boilerplate.
Web components at BeBranded
Reusable components are the base of a maintainable product, whichever stack is chosen. When we build a web app, our team decides case by case between native web components and a framework, based on reuse needs, performance and the skills of the client team.