Web Components: Custom Elements, Shadow DOM and Slots
Build a themed star-rating custom element with a template, shadow DOM and slots, expose its theming API through custom properties and ::part, and use it from React.
Contentsand lesson path
On this page
- The brief
- Step 1: register the element and attach a shadow root
- Step 2: attributes, and an event that crosses the boundary
- Step 3: what crosses the boundary — and what does not
- Step 4: use it from React
- Ways this goes wrong
- Check your understanding
- Apply it
- Review prompt
Lessons of Styling at Scale & Design Systems
- Design Tokens and Theming with Custom Properties Worked example · 25 min
- Comparing Styling Strategies: Modules, Utilities, Layers Concept · 20 min
- Designing Component APIs: Variants, Slots and States Concept · 20 min
- Lab: A Themed Button, Field and Dialog Kit in Storybook Lab · 30 min
- Web Components: Custom Elements, Shadow DOM and Slots Worked example · 25 min
- Check: Review a Component Library Pull Request Knowledge check · 8 questions
What you will learn
- Build a framework-agnostic custom element with a template, shadow DOM and slots, theme it through custom properties and ::part, and use it from a React app.
Prerequisites: CSS Cascade & Box Model
01. The brief
The design system from the previous lessons lives in React — but the design team keeps a rating widget that shows up in the marketing site, which is plain HTML, and in the React app, and next year maybe in the docs generator. Rewriting it per stack invites drift: three copies, three sets of bugs, three slightly different looks. The platform answer is a web component: a custom element the browser itself registers, whose styles are encapsulated by shadow DOM, and which every framework (and no framework) can use the same way.
This worked example builds <star-rating>: five buttons in shadow DOM, a slotted label, theming through custom properties and ::part, and a star-change event that crosses the boundary. At the end, a React 19 app renders it and receives the event — with no adapter library, because the integration points are the platform's.
The files run in a real browser. Because the element is loaded as a module script, serve the folder rather than opening the file directly — npx serve is enough, and the verification script in this lesson starts its own server to prove the behaviour.
02. Step 1: register the element and attach a shadow root
const template = document.createElement('template');
template.innerHTML = `
<style>
:host { display: inline-flex; gap: 4px; align-items: center; }
.label { font: 14px system-ui, sans-serif; margin: 0;
color: var(--star-label-color, #4a5560); }
.star {
all: unset;
font-size: var(--star-size, 20px);
line-height: 1;
cursor: pointer;
color: var(--star-color, #93a1b0);
}
.star[aria-pressed='true'] { color: var(--star-color-active, #b7791f); }
.star:focus-visible {
outline: 2px solid var(--star-focus, #1a5ec2);
outline-offset: 2px;
}
</style>
<p class="label"><slot>Rating</slot></p>
<div class="stars" role="group" aria-label="Rating"></div>
`;A <template> holds the static skeleton: shadow styles and the shape of the widget. Note the token discipline from the first lesson, now with a twist — every var() has a fallback value, because the component must look right on a page that has never heard of it. The :host selector styles the element itself from inside its own shadow root.
The element's name must contain a hyphen (star-rating), so the browser can tell custom elements apart from built-ins. Registration looks like this:
class StarRating extends HTMLElement {
static observedAttributes = ['value'];
#value = 0;
#stars = [];
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.append(template.content.cloneNode(true));
const box = this.shadowRoot.querySelector('.stars');
for (let i = 1; i <= 5; i++) {
const star = document.createElement('button');
star.type = 'button';
star.className = 'star';
star.part.add('star');
star.setAttribute('aria-label', `Rate ${i} of 5`);
star.textContent = '\u2605';
star.addEventListener('click', () => {
this.value = i;
});
box.append(star);
this.#stars.push(star);
}
}attachShadow is the encapsulation switch: from this moment the element renders its shadow tree, and the page's stylesheets cannot match anything inside it. Each star is a real <button> — keyboard reachable, with its own accessible name — and part.add('star') exports it to the page's CSS, which we will use in a moment. A clone of the template per instance matters: template.content itself must never be appended directly, or the second instance would steal the first one's DOM.
03. Step 2: attributes, and an event that crosses the boundary
get value() {
return this.#value;
}
set value(next) {
// Route writes through the attribute: one source of truth.
this.setAttribute('value', String(next));
}
attributeChangedCallback(name, _old, next) {
if (name !== 'value') return;
this.#value = Number(next) || 0;
this.#stars.forEach((star, index) => {
star.setAttribute(
'aria-pressed',
index < this.#value ? 'true' : 'false',
);
});
this.dispatchEvent(
new CustomEvent('star-change', {
detail: this.#value,
bubbles: true,
}),
);
}
}
customElements.define('star-rating', StarRating);Writes go through the attribute, so HTML (value="3"), JavaScript (el.value = 4) and a framework all land on one code path: attributeChangedCallback re-paints the pressed states and dispatches star-change. Notice the event boundary: this.dispatchEvent(...) runs on the host element itself, which is already in the outer light DOM, so bubbles: true allows the event to bubble up through parent containers to document. If an event were instead dispatched from a node inside the shadow root (such as the internal <button> star), composed: true would be required for the event to cross the shadow root boundary into the light DOM.
04. Step 3: what crosses the boundary — and what does not
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>star-rating experiments</title>
<style>
/* 1. Document styles cannot match inside a shadow root. */
star-rating .star { color: hotpink; font-size: 40px; }
/* 2. Custom properties cross: this is the theming API. */
star-rating.themed { --star-color-active: #0f766e; --star-size: 28px; }
/* 3. ::part() styles the exposed parts from the page. */
star-rating.themed::part(star):hover { transform: scale(1.15); }
</style>
<script type="module" src="star-rating.js"></script>
</head>
<body>
<star-rating id="plain" value="3"></star-rating>
<star-rating id="themed" class="themed" value="2">Overall satisfaction</star-rating>
</body>
</html>The first element has a value but no theme and no label; the second is themed and slots a label in. To read what actually rendered, the script below serves the folder on a free local port, reads computed styles inside each shadow root, and clicks a star while listening for star-change. Set the folder up once with npm init -y, npm pkg set type=module, npm install [email protected] [email protected], npm install -D [email protected] [email protected] and npx playwright install chromium; React and esbuild are for step 4.
import { createServer } from 'node:http';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';
import { chromium } from 'playwright';
// A tiny static server for this folder: module scripts do not load from file://.
const types = { '.html': 'text/html', '.js': 'text/javascript' };
const server = createServer(async (req, res) => {
try {
const file = join(process.cwd(), new URL(req.url, 'http://x').pathname);
const body = await readFile(file);
res.writeHead(200, { 'content-type': types[extname(file)] ?? 'text/plain' });
res.end(body);
} catch {
res.writeHead(404).end();
}
}).listen(0, '127.0.0.1');
await new Promise((resolve) => server.once('listening', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(`${base}/page.html`);
await page.waitForFunction(() => customElements.get('star-rating'));
const star = (id) => page.$eval(`#${id}`, (el) => {
const s = getComputedStyle(el.shadowRoot.querySelector('.star'));
const slot = el.shadowRoot.querySelector('slot');
const label = slot.assignedNodes().length
? slot.assignedNodes().map((n) => n.textContent).join('').trim()
: slot.textContent;
return { color: s.color, size: s.fontSize, label };
});
const plain = await star('plain');
console.log(`untouched element: star color=${plain.color} size=${plain.size}`);
console.log(' (page rule .star{color:hotpink;font-size:40px} had no effect)');
console.log(` slot fallback label: "${plain.label}"`);
const themed = await star('themed');
console.log(`themed element: star color=${themed.color} size=${themed.size}`);
console.log(` slotted label: "${themed.label}"`);
const event = page.evaluate(() => new Promise((resolve) => {
document.addEventListener('star-change',
(e) => resolve(`detail=${e.detail} target=${e.target.tagName}`), { once: true });
}));
await page.locator('#themed').getByRole('button', { name: 'Rate 1 of 5' }).click();
console.log(`after click: star-change ${await event}`);
if (existsSync('react.bundle.js')) { // built in step 4
await page.goto(`${base}/react.html`);
await page.getByRole('button', { name: 'Rate 4 of 5' }).click();
// React re-renders after the event; give it up to 2 s to leave the initial 0.
await page.waitForFunction(() => !document.body.innerText.includes('this 0 of'),
null, { timeout: 2000 }).catch(() => {});
const text = await page.getByText(/^You rated this/).textContent();
console.log(`react page: "${text}"`);
}
await browser.close();
server.close();untouched element: star color=rgb(183, 121, 31) size=20px
(page rule .star{color:hotpink;font-size:40px} had no effect)
slot fallback label: "Rating"
themed element: star color=rgb(15, 118, 110) size=28px
slotted label: "Overall satisfaction"
after click: star-change detail=1 target=STAR-RATINGThe measurements say it all. The hotpink, 40px page rule never lands — the computed star keeps the component's own colours, --star-color-active's fallback gold at 20px. On the themed instance the page's custom properties flow in (rgb(15, 118, 110) is #0f766e) because inheritance crosses the shadow boundary even though selector matching does not. ::part(star) gives the host page a styling hook for anything the custom properties cannot express, such as the hover scale. The first element shows the slot fallback Rating; the second has a child, "Overall satisfaction", which the default slot distributes into the label. And the click reports target=STAR-RATING: dispatched on the host with bubbling enabled, the event arrives addressed to the component.
Slots are the second half of the composition story from the component-API lesson — the platform version. The shadow template declares <slot> where caller content belongs; light-DOM children fill it, and the slot's fallback content renders when there is nothing to distribute. Named slots (<slot name="title">) plus the slot attribute give a component several regions, exactly like children props in React — but at the DOM level, so any stack can fill them.
05. Step 4: use it from React
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
import './star-rating.js'; // registers the element; no plugin needed
function App() {
const [rating, setRating] = useState(0);
return (
<>
{/* React 19 binds custom events directly via JSX attributes */}
<star-rating
value={rating}
onstar-change={(event) => setRating(event.detail)}
/>
<p>You rated this {rating} of 5.</p>
</>
);
}
createRoot(document.getElementById('root')).render(<App />);Browsers cannot load JSX or the bare react import directly, so bundle react.jsx once with esbuild and load the bundle from a small page:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>star-rating in React</title></head>
<body>
<div id="root"></div>
<script type="module" src="react.bundle.js"></script>
</body>
</html>npx esbuild react.jsx --bundle --format=esm --jsx=automatic \
--outfile=react.bundle.js
node verify.mjsreact page: "You rated this 4 of 5."React 19 brings first-class support for custom elements in JSX: it checks custom element instances for matching property setters (setting el.value = rating directly instead of string attribute conversion), and binds custom event handlers natively in JSX matching the event name — here onstar-change={(event) => setRating(event.detail)}. In older React versions (prior to React 19), custom events required attaching a manual event listener via a ref inside a useEffect hook. The last line of the verification output — react page: "You rated this 4 of 5." — is the loop closing: a click inside the custom element updated React state through a platform event.
06. Ways this goes wrong
07. Check your understanding
08. Apply it
This is the last piece of the skill's practice task — the widget shipped alongside the React kit.
- Give
<star-rating>alabelattribute that replaces the slot for cases where the caller wants plain text, keeping the slot as the default. Which wins when both are set, and can you express that rule in code rather than documentation? - Add a
readonlyattribute that disables the buttons but keeps the display. Check the widget still exposes the rating to assistive technology when not interactive. - Point the shadow styles at the kit's real tokens (
var(--color-primary)without a fallback), then render the element on a page that loadstokens.cssand on one that does not. Decide which behaviour you want, and document the contract.
09. Review prompt
Without looking back: which two CSS mechanisms let a page theme a shadow-DOM component, and which mechanism does it not get? What must an event carry to leave a shadow root? What does a slot render when nothing is slotted? And what does React 19 do with the value prop of a custom element that defines a setter?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.