Designing Component APIs: Variants, Slots and States
Design the props of a reusable component so invalid combinations cannot compile, composition beats configuration, and every state — including focus and error — is deliberate.
Contentsand lesson path
On this page
- Why it matters
- Variants: one choice per axis
- Make invalid states unrepresentable
- Slots: composition over configuration
- States: every one reachable, none colour-only
- 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 reusable, accessible components with typed variant APIs and document every state in a component workshop such as Storybook.
Prerequisites: CSS Cascade & Box Model
01. Why it matters
A component library is an API that renders pixels. Once a button has forty call sites, every weakness in its props is a bug factory: a boolean that can be set alongside its sibling, an escape hatch that lets one team paste the old styles back, a state that exists in the design file but that no markup can express. The API is where accessibility either becomes automatic — a label that must be provided, a focus ring that cannot be removed — or gets delegated to whoever is in a hurry.
The tools are the ones you already know from typed React components: union types, composition, and required props. What this lesson adds is the design judgement: which axes deserve a variant, when children beat props, and why every visual state needs to be reachable and documented. Everything is checked with the TypeScript compiler and a real accessibility tree, not with good intentions.
02. Variants: one choice per axis
// Axis 1: variant as a union — one choice per axis.
type Variant = 'primary' | 'secondary' | 'danger';
type Size = 'sm' | 'md' | 'lg';
interface ButtonProps {
variant?: Variant;
size?: Size;
children: string;
}
declare function Button(props: ButtonProps): string;
Button({ children: 'Send', variant: 'primary', size: 'md' });
Button({ children: 'Send', variant: 'prmary' }); // typo on an axisbutton-api.ts(14,28): error TS2820: Type '"prmary"' is not
assignable to type 'Variant | undefined'. Did you mean
'"primary"'?A union type makes each visual axis a single, checked choice. The compiler catches the typo before the code runs — and suggests the fix. Contrast that with the boolean style, primary?: boolean; danger?: boolean, where primary: true, danger: true compiles in silence: the two flags fight in CSS order, and the winner depends on which rule comes last in a file nobody meant to decide the question. Booleans also keep multiplying: the moment design asks for a "quiet" variant, three more combinations appear that nobody designed.
One axis, one union. When a genuine combination is needed — a danger and small button — those are different axes, each with its own union, and the valid pairs are exactly the cross product you designed.
03. Make invalid states unrepresentable
// Axis 3: a discriminated union — the shape carries the rule.
type Prompt =
| { kind: 'label'; text: string }
| { kind: 'icon'; label: string }; // an icon button must be named
declare function Confirm(prompt: Prompt): string;
Confirm({ kind: 'label', text: 'Delete note' });
Confirm({ kind: 'icon', label: 'Delete note' });
Confirm({ kind: 'icon' }); // icon with no accessible namebutton-api.ts(24,9): error TS2345: Argument of type
'{ kind: "icon"; }' is not assignable to parameter of type 'Prompt'.
Property 'label' is missing in type '{ kind: "icon"; }' but
required in type '{ kind: "icon"; label: string; }'.An icon-only button with no accessible name is invisible to a screen reader — one of the most common accessibility bugs in real products. Instead of hoping call sites remember, the API makes the rule part of the type: the icon shape requires a label. The compiler turns an accessibility review comment into a build failure, at every call site, forever. The same discriminated-union trick fits any "this mode requires that data" rule: a dialog that must be labelled, a table that must know its columns.
04. Slots: composition over configuration
Variant props describe a closed set of appearances. The moment a component starts collecting props for content — title, subtitle, footerNote, actionLabel, then showDivider — it is re-implementing HTML one prop at a time, and every new design request becomes a new prop and a release. The escape is composition: accept children (and named regions where the layout demands them) and let the caller bring any markup they need.
A practical split that holds up well:
- Variants for closed sets the design system actually drew: colour, size, emphasis.
- Slots for open content: whatever goes inside the card, dialog or field wrapper.
- Escape hatches rarely: a free-form
classNameon a styled component lets callers paste the old stylesheet back and quietly opt out of the system. Some layout-only escape hatch may be justified; it should be named for the job it does, and the default should be the design.
This is the React side of the idea; the last lesson in this skill meets the platform version of slots inside web components, where the same principle is built into the browser.
05. States: every one reachable, none colour-only
A styled component has states beyond its variants: hover, focus, disabled, loading, error. Three rules keep them honest. First, every state must be reachable from real use — a focus style nobody can trigger is documentation, not design. Second, no state may be signalled by colour alone: an error gets an icon or text as well as red, or colour-blind readers lose the signal (the web accessibility skill covers this rule as WCAG 1.4.1). Third, focus must be visible for keyboard users, and the :focus-visible pseudo-class is how you scope the ring to keyboard interaction rather than annoying mouse users.
<button class="button" type="button" aria-label="Delete note">
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
<path d="M2 4h12M6 4V2h4v2M4 4l1 10h6l1-10" fill="none"
stroke="currentColor" stroke-width="1.5" />
</svg>
</button>
<!-- the second button is identical, but without aria-label -->To see both facts in a real browser, set up a folder with npm init -y, npm pkg set type=module and npm install -D [email protected] (plus npx playwright install chromium once), and save the script below as verify.mjs. It renders the two buttons, prints the accessibility tree Chromium builds for them, then focuses the first button with Tab and the second with a click.
import { chromium } from 'playwright';
const svg = '<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">' +
'<path d="M2 4h12M6 4V2h4v2M4 4l1 10h6l1-10" fill="none" stroke="black"/></svg>';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(
`<button class="button" type="button" aria-label="Delete note">${svg}</button>` +
`<button class="button" type="button">${svg}</button>`,
);
console.log('accessibility tree:');
console.log(await page.locator('body').ariaSnapshot());
const focusVisible = () =>
page.evaluate(() => document.activeElement.matches(':focus-visible'));
await page.keyboard.press('Tab');
console.log(`focus via Tab: :focus-visible = ${await focusVisible()}`);
await page.locator('button').nth(1).click();
console.log(`focus via click: :focus-visible = ${await focusVisible()}`);
await browser.close();accessibility tree:
- button "Delete note"
- button
focus via Tab: :focus-visible = true
focus via click: :focus-visible = falseThe accessibility tree is what assistive technology reads, and the browser builds it for you: the labelled button gets its name, the identical button without one is just button — a dead end for a screen-reader user. The :focus-visible check shows the mechanism working: keyboard focus turns the selector on, mouse focus does not, so the ring appears exactly where it helps. A component library verifies both things once, in stories, instead of hoping every product team does.
06. Ways this goes wrong
07. Check your understanding
08. Apply it
You will use these rules on the kit in the lab later in this skill.
- Take one component you have built and list its props. Mark each as variant, content or escape hatch, and rewrite any boolean soup as a union axis.
- Find one place where the type system can carry an accessibility rule (a required label, a mandatory description) and make it a compile error instead of a convention.
- Run your component in a browser, tab through it, and check the accessibility tree (Playwright's
ariaSnapshot()or DevTools) shows a name for every control in every state.
09. Review prompt
Without looking back: why does a union prop beat booleans for a visual axis? What does a discriminated union add to a plain union? Where is the line between a variant and content that belongs in children? And which two checks prove a focus style works for keyboard users?
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.