Web components

On this page 8

Web components are a family of native browser standards that let developers define their own reusable custom HTML elements, with private markup, private styles and their own behavior. In the Web platform, they turn a piece of interface such as a date picker or a product card into a tag like <date-picker> that any page can use, regardless of whether it was built with a framework or with plain HTML and JavaScript.

The term covers three core specifications that work together: Custom Elements, Shadow DOM and HTML templates. Because these are built into every modern browser, a web component requires no runtime library to work, which makes the approach attractive for design systems and widgets that must outlive any single framework.

How web components work

A web component works by registering a JavaScript class with the browser under a tag name, then letting the browser create an instance of that class every time the tag appears in the DOM. The class usually extends HTMLElement and is registered with customElements.define('user-card', UserCard). From that moment, the parser treats <user-card> as a first-class element with its own properties, methods and events.

Inside the class, the component typically attaches a shadow root with this.attachShadow({mode: 'open'}) and renders its internal structure there. That internal tree is hidden from the surrounding document, so outside CSS does not leak in and internal styles do not leak out. A <template> element can hold inert markup that the component clones on creation, which is faster than rebuilding the structure from strings.

The following table summarizes the building blocks and the role each one plays.

SpecificationWhat it providesKey API
Custom ElementsNew tag names with lifecycle and behaviorcustomElements.define()
Shadow DOMEncapsulated subtree with scoped stylesattachShadow()
HTML templatesInert, reusable markup fragments<template> and <slot>
ES modulesStandard way to load component codeimport and export
Core specifications behind web components

Lifecycle callbacks and the component API

Custom elements expose lifecycle callbacks that the browser calls at defined moments, which gives authors precise control over setup and cleanup. Code that touches the DOM or adds listeners belongs in connectedCallback, and anything that must be released belongs in disconnectedCallback, otherwise memory leaks appear in long-lived single-page applications.

CallbackWhen it runsTypical use
constructorElement is created or upgradedInitialize state, attach shadow root
connectedCallbackElement is inserted into a documentRender, fetch data, add listeners
disconnectedCallbackElement is removed from a documentRemove listeners, cancel timers
attributeChangedCallbackAn observed attribute changesSync attribute to internal state
adoptedCallbackElement moves to another documentRare; adjust document-specific state
Custom element lifecycle callbacks

A well-designed component communicates through a clear public contract: attributes and properties carry data in, and custom events carry notifications out. Only attributes listed in the static observedAttributes array trigger attributeChangedCallback. Attributes are always strings, so rich data such as arrays or objects should be passed as JavaScript properties rather than serialized into markup.

Styling, slots and encapsulation

Encapsulation in web components means that the shadow tree has its own style scope, so a selector such as p { color: red; } on the page does not affect paragraphs inside the component. This isolation is the main reason design systems adopt the technology, but it also means that authors must provide deliberate styling hooks for consumers.

  • CSS custom properties inherit through the shadow boundary, so variables like --card-accent are the standard theming channel.
  • The ::part() pseudo-element exposes named internal parts that page styles may target.
  • The :host selector styles the component element itself from inside the shadow root.
  • Slots project light DOM children into placeholders, and ::slotted() styles those projected nodes.

Slots deserve special attention because they keep content in the light DOM, where it remains visible to search engines, accessible to page scripts and styled by page CSS. A <slot name="title"> placeholder receives any child marked slot="title", which lets one component accept rich content without copying it into its private tree.

Web components compared with framework components

Web components differ from React, Vue or Angular components mainly in where the component model lives: in the browser rather than in a library. Framework components offer richer state management and templating, while web components offer interoperability and longevity because the platform guarantees backward compatibility.

AspectWeb componentsFramework components
Runtime dependencyNone beyond the browserFramework library required
InteroperabilityUsable in any framework or noneTied to one framework
Style isolationNative through Shadow DOMConventions or build tooling
Reactive stateManual or via small helper librariesBuilt into the framework
Server-side renderingDeclarative Shadow DOM, still maturingMature in most frameworks
Web components and framework components side by side

In practice, the two approaches are complementary rather than competing. Many teams author low-level design system elements as web components and consume them inside framework applications. Helper libraries such as Lit or Stencil add reactive properties and efficient rendering on top of the standards while still producing genuine custom elements.

Accessibility, forms and server rendering

Accessibility does not come for free with web components, because a custom tag has no implicit role or keyboard behavior. An author who builds a <fancy-button> must add role, tabindex, focus styles and key handling, or better, wrap a real <button> inside the shadow root so the browser supplies native semantics automatically.

Form participation was historically a weak point, since inputs inside a shadow root were invisible to the parent <form>. Form-associated custom elements solve this: setting static formAssociated = true and calling attachInternals() lets a component submit values, report validity and respond to form reset like a native control. Similarly, Declarative Shadow DOM with <template shadowrootmode="open"> allows servers to send a pre-rendered shadow tree, removing the flash of unstyled content that client-only rendering causes.

Common mistakes and limitations

Most problems with web components come from treating them like framework components or ignoring the rules of the platform. The table below lists frequent symptoms and their fixes.

SymptomLikely causeFix
define throws an errorTag name lacks a hyphen or is registered twiceUse a hyphenated name and guard with customElements.get()
Page styles do not apply insideShadow DOM encapsulation working as designedExpose custom properties or ::part()
Screen readers announce nothing usefulMissing roles and labelsWrap native elements or add ARIA
Listeners fire after removalNo cleanup in disconnectedCallbackRemove listeners and abort requests
Rich data arrives as textObject passed through an attributePass data through a property
Typical web component problems and remedies

There are also genuine limitations. Global stylesheets and some CSS frameworks do not reach into shadow roots, so utility-class workflows need adaptation. Tag names live in a single global registry, which can cause collisions when two libraries define the same name; scoped custom element registries are being standardized to address this.

In plain words

Web components let developers invent their own HTML tags. Imagine a building kit where you can design a new kind of brick once, with its own color and shape, and then use that brick in any house you build. A web component is that reusable brick for web pages.

Each custom tag carries its own look and behavior inside a protected shell, so the rest of the page cannot accidentally change it. Because browsers understand these tags natively, the same component works on almost any website, whether it was made with a popular framework or with plain code.

A real-world example

A mid-sized bank runs four customer-facing applications: an older server-rendered site, two React applications and a newer Vue dashboard. Its design team needs buttons, alerts and account cards to look identical everywhere, but maintaining four separate component libraries has produced visible inconsistencies and duplicated effort.

The team rebuilds about 30 core interface pieces as web components, such as <bank-button> and <bank-alert>, using Shadow DOM for isolation and CSS custom properties for brand colors. Each component wraps native elements to keep keyboard and screen reader support, and form controls use form-associated custom elements so they submit like ordinary inputs.

Within two release cycles, all four applications load the same package. A brand color change now ships by updating one CSS variable instead of four codebases, and the result is a single design system shared across every framework the bank uses.