What you'll learn: By the end of this lesson you will be able to explain the three browser features behind web components, say what the shadow boundary hides and what it lets through (styles, events, ids, focus), choose between custom properties,
partand slots for customising a component, make a custom element take part in a form, and decide when a web component beats a framework component.
Think of a hotel room. Guests rearrange the furniture without the hotel noticing, and the hotel repaints the corridor without the guests noticing. The door is the boundary. A few things pass through it on purpose: the thermostat on the wall, a hatch for room service, a phone line. A web component is a room with a door. The shadow DOM is the door, slots are the hatch, and a few documented routes (CSS custom properties, part names, events) are the phone line.
The running example is the product page of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a price tag and a quantity stepper that the design-system team wants to reuse in a React app and in a plain marketing page.
The core idea
- Custom elements give you a new HTML tag with your own behaviour. You write a class and register it under a name with a hyphen.
- The shadow DOM hides the inside of a component. Page CSS does not reach in, component CSS does not leak out, and
document.querySelector()does not find the internals. - The boundary leaks in a few documented places. Slotted children, inherited properties, custom properties,
partnames, composed events and form association are the ways in and out.
MDN lists three technologies: custom elements (JavaScript APIs to define elements and their behaviour), shadow DOM (an encapsulated tree attached to an element) and templates with slots (markup that is not rendered until used). Its steps are: define a class, register it with customElements.define(), attach a shadow DOM, optionally clone a template into it, then use the tag like any other.
Figure 1. A component: host, shadow tree and slotted children
How to read this: the accent box is what the page sees. Its private tree (top right) is invisible to page CSS and to querySelector. The children the page puts inside the tag are not moved: they are drawn in a slot, which is why page CSS can still style them.
Custom elements
An autonomous custom element extends HTMLElement. A customized built-in extends a standard element and is used with is; MDN notes Safari does not plan to support those, so libraries mostly use autonomous elements. The name must start with a lowercase letter and contain a hyphen.
MDN's lifecycle callbacks: connectedCallback() runs each time the element is added to the document (the specification recommends setup there, not in the constructor), disconnectedCallback() each time it is removed, adoptedCallback() when it moves to a new document, and attributeChangedCallback() when an attribute listed in static observedAttributes changes. In the constructor you may set state, register listeners and create a shadow root, but should not inspect or add attributes or children. Moving an element with insertBefore() fires disconnectedCallback() then connectedCallback(), so setup must be safe to repeat and undone on disconnect.
Figure 2. Lifecycle of a custom element
How to read this: the constructor runs before the element is in the document, so it cannot rely on attributes or children. Render in the two callbacks and undo what you started in disconnectedCallback().
Illustration 1: the minimal example
A price tag with a shadow tree, one part and one slot. These snippets were written from the MDN pages cited below and were not run for this lesson: it ships no lab, and Node has no DOM, so no output is shown.
class PriceTag extends HTMLElement {
static observedAttributes = ["amount"];
#amount = document.createElement("span");
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
this.#amount.part.add("amount");
root.append(this.#amount, document.createElement("slot"));
}
attributeChangedCallback(name, oldValue, newValue) {
this.#amount.textContent = newValue ?? "";
}
}
customElements.define("price-tag", PriceTag);
Used as <price-tag amount="4.20"><small>per kg</small></price-tag>, the span shows the attribute and the small element is drawn in the slot. Text goes in with textContent, not innerHTML, so an attribute value can never become markup (see XSS defenses).
The shadow DOM and what it hides
MDN's terms: the shadow host is the node the tree is attached to, the shadow root is the tree's root, and the shadow boundary is where the shadow DOM ends and the regular DOM begins. attachShadow({ mode }) takes open (the host's shadowRoot property returns the root) or closed (it returns null). MDN says not to treat closed as a strong security mechanism, because browser extensions, for example, can evade it.
Per MDN, document.querySelectorAll() does not find shadow elements, page styles do not affect them, and shadow styles do not affect the page. The CSS Shadow Module adds that selectors inside a shadow tree cannot see outside it. This solves the collision problem that the CSS architecture lesson attacks with naming rules and layers, with a wall instead of a convention.
A shadow root can also be written in HTML: a template with shadowrootmode is replaced when parsed by its content wrapped in a shadow root, so a server can ship a shadow tree. Check your framework's support; see Rendering Strategies.
Templates and slots
A template's content is not rendered; MDN's pattern appends a clone made with document.importNode(template.content, true) to the shadow root. A slot is a placeholder that light-DOM children fill: an element with slot="note" goes to <slot name="note">, elements with no slot attribute go to the unnamed default slot, and an empty slot shows its fallback content. Names should be unique per shadow root.
Slotted children stay children of the host in the light DOM; only where they are drawn changes. So page CSS can style them, and the component reaches them with ::slotted(), which per MDN works only in shadow CSS and matches elements, not text nodes.
Styling across the boundary
| Route | Direction | How it works | Limit |
|---|---|---|---|
| Inherited properties | Page to component | Inheriting properties (such as color) continue through the host |
Non-inherited ones (such as border) do not pass |
| CSS custom properties | Page to component | The component reads var(--price-color, black); the page sets it on the host or above |
The component must opt in and give fallbacks |
part and ::part() |
Page to component | The component marks part="amount"; the page styles price-tag::part(amount) |
:hover works, structural pseudo-classes do not; no chained ::part() |
| Slots | Both | The page supplies content that stays in its own DOM | Only what the component slots |
The first two rows rest on MDN's inheritance statements plus the Shadow Module's flattened tree; no source read here spells out each property, so treat them as the documented rules applied. Part names are visible only to the direct parent unless re-exported with exportparts.
For a component's own styles, use a style in the template, or a constructable stylesheet (new CSSStyleSheet(), replaceSync(), shadowRoot.adoptedStyleSheets) that many trees share and the browser parses once; MDN lists it as Baseline widely available since March 2023. Inside the tree, :host selects the host.
Figure 3. Which styling hook to offer
need to change?"} A -->|"a value: colour, size"| B["CSS custom property
with a fallback"] A -->|"any style of one element"| C["part attribute
and ::part()"] A -->|"the content itself"| D["slot"] A -->|"nothing documented"| E["Keep it private"]
How to read this: every hook is a promise. A custom property exposes one value, a part exposes every style of an element, and a slot hands over content. Whatever you do not expose stays free to change.
Events across the boundary
Whether an event leaves a shadow tree depends on its composed flag. MDN says all browser-dispatched UI events (click, touch, mouseover, copy, paste) are composed and most others are not, including synthetic events created without composed: true. Crossing also needs bubbles: true; if the event is not composed, the shadow root is the last node offered it.
There is a second effect, retargeting. The DOM specification's algorithm replaces an object with its root's host while it sits inside a shadow tree, so a listener outside sees the host as event.target, not the inner button. composedPath() lists the objects on which listeners will be invoked, and omits shadow nodes when the root is closed. Event delegation therefore sees the host, not the inner element, across a boundary.
Figure 4. An event leaving a component
How to read this: user events cross the boundary by default. Your own events do not, unless you set composed: true with bubbles: true, or dispatch on the host.
Forms, labels and focus
The platform's built-in connections assume one flat tree, so encapsulation costs most here.
- Forms. A custom element joins a form with
static formAssociated = trueandattachInternals(). MDN saysElementInternalslets custom elements fully participate in HTML forms:setFormValue()sets the submission value,setValidity()the validity. The element supplies its own value; do not count on an inner input. See Form State and Validation. - Id references. MDN says attribute references such as
aria-labelledbyandforcan only point to elements in the same DOM or shadow DOM, because ids are valid only in the scope where they are declared. A pagelabel forcannot name an input inside a shadow tree. Reflected ARIA properties can target the same or a parent DOM, but not a nested shadow tree. - Default semantics.
ElementInternalsalso exposesrole,ariaLabeland other ARIA properties, so defaults survive if the author removes attributes. - Focus. With
delegatesFocus: true, MDN says clicking a non-focusable part or calling.focus()on the host focuses the first focusable element inside.
A shadow tree gives isolation, not accessibility. WCAG 2.2 criterion 4.1.2, Name, Role, Value (level A), covers components "generated by scripts": name and role must be programmatically determinable and state changes available to assistive technology. Names, keyboard and focus are the subject of the accessibility lessons of module F14; here only the shadow-boundary changes are covered.
Inside React
React's reference says a tag with a dash renders as a custom element. JSX values are passed as attributes by default (an array becomes a string); React passes properties when the name exists on the class during construction. Custom events are heard with an on prefix and the exact name, dashes kept (onqty-change). So design the public API as attributes for simple values, properties for rich ones and events for output, and it works in any framework or none. See also Component-Based Architecture.
Illustration 2: the realistic example
The quantity stepper for the product page: form-associated, one custom property, one part, one event. Also not run.
class QtyStepper extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
#value = 1;
#shown = document.createElement("output");
constructor() {
super();
const root = this.attachShadow({ mode: "open", delegatesFocus: true });
const style = document.createElement("style");
style.textContent = "button { min-width: var(--qty-target, 24px); min-height: var(--qty-target, 24px); }";
const minus = Object.assign(document.createElement("button"), { type: "button", textContent: "-" });
const plus = Object.assign(document.createElement("button"), { type: "button", textContent: "+" });
minus.setAttribute("aria-label", "Decrease quantity");
plus.setAttribute("aria-label", "Increase quantity");
this.#shown.part.add("value");
minus.addEventListener("click", () => this.#set(this.#value - 1));
plus.addEventListener("click", () => this.#set(this.#value + 1));
root.append(style, minus, this.#shown, plus);
this.#set(1);
}
#set(next) {
this.#value = Math.max(1, next);
this.#shown.textContent = String(this.#value);
this.#internals.setFormValue(String(this.#value));
this.dispatchEvent(new CustomEvent("qty-change", { detail: { value: this.#value }, bubbles: true }));
}
}
customElements.define("qty-stepper", QtyStepper);
setFormValue() puts the value in the form's submission; delegatesFocus forwards focus to the first button; the part lets the page style the number; --qty-target with a fallback lets a design system enlarge the buttons, for instance toward the 24 by 24 CSS pixel minimum of WCAG 2.2 criterion 2.5.8 (level AA, with exceptions); the event is dispatched on the host, so it needs no composed flag. The labels sit on the buttons because a page-level label could not reach them.
Illustration 3: a failure
Two quiet breaks. Someone moves the dispatch to the inner button with only bubbles: true: the event is not composed, so it stops at the shadow root and the page's listener silently stops firing. A form author writes label for="qty" for an input inside the tree: ids are valid only in their own scope, so the reference cannot reach it. Neither raises an error; a test that uses the component from outside, as the page does, finds both.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Web component with shadow DOM | One implementation for any framework; real style isolation | Forms, labels and focus need explicit work; styling only through hooks you design |
| Framework component | Best experience inside one framework | Tied to it; isolation by convention |
| Many parts and properties | Easy theming | A large API to keep stable |
Build it
This lesson has no lab. Running a component needs a real browser, and browser automation is not part of this course's local tooling, so no behaviour here was observed and no output is claimed. To try the snippets, put one in an HTML page and inspect the shadow tree in a browser's developer tools.
In practice: sharing a stepper between two front ends
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The product page is a React app; the marketing site is server-rendered HTML with a little script. Both need the same stepper. Today there are two implementations that drift: the marketing copy does not submit its value in the add-to-cart form.
Starting architecture
Figure 5. Two copies of one component
How to read this: the warning boxes are two copies of the same behaviour that only share a written spec, so they drift. The red edge is the copy that loses the quantity on submit.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep two copies, add tests | No migration | Two codebases | Drift returns |
| Shadow-DOM web component | One behaviour, isolated styles | Form, label and focus work; a styling API | Gaps in React and server rendering |
The decision
| Field | Decision record |
|---|---|
| Context | Two stepper copies drift; one drops the quantity on submit. |
| Decision | Build qty-stepper as a form-associated custom element with an open shadow root. Public API: the attribute, --qty-target, the value part and the qty-change event. |
| Consequences, good | One behaviour on both sites; the form gets the value; target size is a token. |
| Consequences, bad | A styling surface to keep stable; labels live inside the component; React needs the attribute and property rules. |
| Revisit when | Both sites share a framework, or server-rendered markup is needed that the approach cannot give. |
Rollout and verification
- Write the public API first, each item with a default.
- Test from outside: submit a form containing it, listen for the event on the document, tab to it.
- Check in React that rich values go as properties and events use the exact name.
- Release on the marketing site first, then replace the React copy, checking with a keyboard and a screen reader.
The 2 a.m. failure
After a release, add-to-cart always submits quantity 1. A late change replaced the form association with an inner input, so the form no longer receives the chosen value.
First three checks: (1) submit the form and read what it sends; (2) look for an inner input standing in for the element's own value; (3) confirm static formAssociated = true and setFormValue() on every change. Mitigation: revert. Follow-up: a test that submits a form containing the component.
Architect's notes
- The boundary is the API. Offer the narrowest hook: custom property for values, part for structure, slot for content.
- Dispatch custom events on the host, or set
bubblesandcomposedtogether. - Own the form and label wiring inside the component.
- Choose a web component when several frameworks or sites share it, a framework component when one app owns it.
Common mistakes
- Using
closedmode as security. - Setup in the constructor that needs attributes or children.
- A custom event from inside the tree without
composed: true. - Expecting page CSS,
label fororaria-labelledbyto reach inside. - Exposing every inner element as a
part. - Assuming a custom element is a form control without
formAssociated.
Key takeaways
- Web components are custom elements, the shadow DOM, and templates with slots.
- The boundary hides markup, ids and styles; inherited and custom properties, parts, slots and composed events cross it.
- Browser UI events are composed; your own are not unless
composed: trueandbubbles: true. - Outside a shadow tree an event's target is the host.
- Forms and labels need explicit work:
formAssociated,ElementInternals, labels inside. - A shadow tree is isolation, not accessibility: WCAG 4.1.2 still applies.
Practice exercises
Exercise 1: Starter (30 min). For a page rule p { color: red; }, a label for to an inner input, a click, and a custom event with only bubbles: true, say whether each crosses a shadow boundary and why.
Exercise 2: Intermediate (2 hours). Choose a hook (custom property, part or slot) for four theming needs of a card component.
Exercise 3: Advanced (half day). Write a compatibility note for the stepper in React: which values are attributes, which properties, how the page listens, and what a test must check from outside.
Related reading
In this course:
- HTML, CSS and JavaScript Architecture: the layers a component sits in.
- CSS Architecture and Scaling: isolation by convention and cascade layers.
- Semantic HTML and Document Structure: the native elements a custom element often should wrap.
- Component-Based Architecture: components in a framework.
- Form State and Validation: the model a form-associated element joins.
Official documentation
- MDN: Web components: the three technologies and the steps.
- MDN: Using custom elements: lifecycle, observed attributes, naming.
- MDN: Using shadow DOM: terms, modes, encapsulation, stylesheets.
- MDN: Using templates and slots: templates, named and default slots.
- MDN: Event.composed and composedPath(): what crosses the boundary.
- MDN: ElementInternals: form association and ARIA defaults.
- React: built-in DOM components, custom HTML elements: attributes, properties and events.