Tutorial

Building a Design System from Scratch

Build a design system that scales: design tokens for a single source of truth, composable components, theming, accessibility, and living documentation.

On this page

  1. Introduction
  2. Design Tokens: The Single Source of Truth
  3. Theming: Light, Dark, and Brand
  4. Components: Composable, Accessible, Token-Driven
  5. Accessibility as a Built-in Property
  6. Documentation: Living, Examples, and Do/Don’t
  7. Governance and the Lifecycle
  8. Testing Components and Adoption Migration
  9. Conclusion

Introduction

A design system is the shared language between design and engineering: a set of tokens, components, and patterns that make a product look and feel coherent and make building UI predictable. Without one, every team reinvents the button, the spacing scale drifts by a pixel per team, and the product accumulates seven shades of the brand blue. With one, a new feature is composed from existing parts, a rebrand is a token change rather than a find-and-replace, and accessibility is built once into the components rather than re-argued per screen. This article builds a design system from scratch: the token layer that is the single source of truth, the component layer that composes from tokens, theming, accessibility as a built-in property, and the documentation that keeps the system alive.

Design Tokens: The Single Source of Truth

A design token is a named, reusable value — a color, a spacing unit, a font size, a radius, a shadow. Tokens are the atoms of the system; everything else is built from them. The value of tokens is indirection: the component does not say color: #2563eb, it says color: var(--color-primary), so when the brand blue changes, the token changes in one place and every component updates. Without tokens, a rebrand is a search for every hardcoded color in the codebase; with tokens, it is a single file.

/* tokens.css — the single source of truth, consumed by every component. */
:root {
  /* Color: a small, named scale, not every shade. */
  --color-primary-50: #eff6ff;
  --color-primary-500: #3b82f6;
  --color-primary-700: #1d4ed8;
  --color-neutral-900: #111827;
  --color-neutral-100: #f3f4f6;
  --color-danger-500: #ef4444;
  --color-focus: #2563eb;

  /* Spacing: a scale based on a base unit, not arbitrary pixels. */
  --spacing-1: 0.25rem;
  --spacing-2: 0.5rem;
  --spacing-3: 0.75rem;
  --spacing-4: 1rem;
  --spacing-8: 2rem;

  /* Typography: a type scale, not one-off sizes. */
  --font-size-sm: 0.875rem;
  --font-size-base: 1rem;
  --font-size-lg: 1.25rem;
  --font-line-height-base: 1.5;

  /* Radius, shadow, motion — each a small scale. */
  --radius-sm: 4px;
  --radius-md: 8px;
  --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
  --transition-fast: 150ms ease;
}

The discipline is to keep the scales small and named. A color scale with nine steps per hue is a scale nobody can remember; three to five steps (50, 500, 700) cover most needs and are learnable. A spacing scale based on a single base unit (--spacing-1 and its multiples) produces rhythm; arbitrary values (13px, 22px) produce noise. Every token should answer “what is this for,” not just “what is its value” — a token named --color-primary-500 is clearer than --blue, and a token named --spacing-4 is clearer than --16px.

Theming: Light, Dark, and Brand

Theming is a token swap. The light theme defines the tokens one way; the dark theme defines them another; the component, written against the token, adapts automatically. The mechanism is CSS custom properties scoped to a selector: the :root holds the light defaults, and a [data-theme="dark"] selector overrides the subset that changes.

:root, [data-theme="light"] {
  --color-bg: var(--color-neutral-100);
  --color-text: var(--color-neutral-900);
  --color-surface: #ffffff;
}
[data-theme="dark"] {
  --color-bg: var(--color-neutral-900);
  --color-text: var(--color-neutral-100);
  --color-surface: #1f2937;
}

The component uses the semantic token (--color-bg, --color-text), not the primitive (--color-neutral-900), because the semantic token is the one that flips between themes. A component that uses --color-neutral-900 directly does not invert in dark mode; a component that uses --color-text does. The layering — primitive tokens (--color-neutral-900) feeding semantic tokens (--color-text) feeding components — is what makes theming a configuration rather than a rewrite. Respect the user’s preference with @media (prefers-color-scheme: dark) as the default, and let an explicit data-theme override it.

Components: Composable, Accessible, Token-Driven

A component is a styled, accessible unit composed from tokens. The button is the canonical example: it uses the primary color token, the medium radius, the base font, and the focus ring, and it is a real <button> so it is keyboard-operable and screen-reader-announced for free.

.button {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-2);
  padding: var(--spacing-2) var(--spacing-4);
  font-size: var(--font-size-base);
  line-height: var(--font-line-height-base);
  border-radius: var(--radius-md);
  border: none;
  cursor: pointer;
  transition: background-color var(--transition-fast);
}
.button--primary { background: var(--color-primary-500); color: white; }
.button--primary:hover { background: var(--color-primary-700); }
.button:focus-visible { outline: 2px solid var(--color-focus); outline-offset: 2px; }
.button:disabled { opacity: 0.5; cursor: not-allowed; }

Two properties make a component system composable. The first is a variant API — button--primary, button--ghost, button--danger — expressed as classes or props, so the consumer chooses the variant without overriding the component’s internals. The second is the slot pattern — the component accepts children rather than hardcoding its content — so the button can contain an icon and text, or just text, without a new component. A component that hardcodes its content is a component that is copied and modified for every variation; a component that slots its content is a component that is reused.

function Button({ variant = "primary", size = "md", children, ...props }: ButtonProps) {
  return <button className={cx("button", `button--${variant}`, `button--${size}`)} {...props}>{children}</button>;
}

Accessibility as a Built-in Property

Accessibility is not a variant of the component; it is a property of every variant. The focus ring is on every button, not just the accessible one. The disabled state uses aria-disabled and cursor: not-allowed, not just a gray color, so screen readers and keyboard users perceive it. The color contrast meets WCAG AA in every theme, verified by a tool in CI, not by a designer’s eye. Building accessibility into the component once means every screen that uses the component inherits it, rather than every screen re-deriving it. Test the components in isolation with axe and with a keyboard, and the system’s accessibility is a property of the system rather than a per-screen audit.

Documentation: Living, Examples, and Do/Don’t

A design system without documentation is a folder of components nobody uses, because nobody knows they exist or how to use them. The documentation that works is living: it renders the actual component, not a screenshot, so the docs and the component cannot drift. It shows an example of each variant and prop, the code to produce it, and a do/don’t pair that shows the right and wrong way to use it. Storybook is the standard tool for this, but a simple markdown page with embedded components works too.

## Button

A button triggers an action. Use it for things the user does, not places the user goes (use a link for navigation).

### Variants
- **Primary**: the main action on the screen. One per screen.
- **Ghost**: a secondary action.
- **Danger**: a destructive action; pair with a confirmation.

### Do
<Example><Button variant="primary">Save changes</Button></Example>

### Don't
<Example><Button variant="primary" onClick={deleteAll}>Delete everything</Button></Example>
Use `variant="danger"` for destructive actions; a primary button labeled "Delete" invites a mistake.

The do/don’t is the most valuable part, because it encodes the judgment a designer would give a developer in a review — “one primary button per screen,” “use danger for destructive actions” — in a form the developer reads at the point of use. Keep the docs next to the component in the repository, so a change to the component prompts a change to the docs in the same pull request.

Governance and the Lifecycle

A design system is a product with users (the other engineers) and a lifecycle. New components are proposed, reviewed, and added when they are general enough to reuse; one-off components stay in the feature that needs them and are promoted to the system only when a second use appears. Version the system and communicate changes, so a consumer can upgrade deliberately rather than discovering their button changed shape. The system that accepts every proposed component becomes a junk drawer; the system that accepts none becomes irrelevant. The balance is a clear bar for inclusion — used in two places, accessible, token-driven, documented — and a maintainer who applies it.

Testing Components and Adoption Migration

A design system is a library, and a library is tested. Component tests fall into three layers: visual tests (does it look right), interaction tests (does it behave right), and accessibility tests (does it work for everyone). Visual tests catch the regression that a style change breaks the appearance — a snapshot or a visual regression tool (Chromatic, Percy) captures the rendered component and flags a pixel-level diff. Interaction tests catch the regression that a behavior change breaks the contract — Testing Library simulates a click and asserts the callback fired. Accessibility tests catch the regression that a markup change breaks the screen-reader experience — axe-core runs against the rendered component and fails on a violation.

import { render, fireEvent } from "@testing-library/react";
import { axe } from "vitest-axe";

test("Button calls onClick when activated by keyboard", async () => {
  const onClick = vi.fn();
  const { getByRole } = render(<Button onClick={onClick}>Save</Button>);
  const button = getByRole("button", { name: "Save" });
  button.focus();
  fireEvent.keyDown(button, { key: "Enter" });
  expect(onClick).toHaveBeenCalledOnce();
});

test("Button has no accessibility violations", async () => {
  const { container } = render(<Button>Save</Button>);
  expect(await axe(container)).toHaveNoViolations();
});

Run the tests against every component variant: every prop combination, every size, every state (default, hover, focus, disabled, loading). A component with five props each with three values has 243 variants; use a matrix or a property-based generator to cover them, and a visual regression tool to capture each. The matrix is the guard that a change to the base styles does not break a variant the developer did not think to test. A component tested only in its default state is a component whose variants are untested, and the variants are where the bugs hide.

Adoption is the long tail of a design system, and it is where most systems fail — not in the building, but in the consuming. A system that is built but not adopted is a system that duplicated the existing components rather than replacing them, and the codebase now has two of everything. The adoption strategy is incremental: identify the highest-traffic pages, replace their components first (the highest impact for the least change), and track the adoption rate (the percentage of pages using the system’s components) as a metric. A rising adoption rate is the signal the system is succeeding; a flat one is the signal it is not, and the reason is usually that the system does not cover a case the consumers need.

// A codemod that replaces raw <button> with the design system <Button>.
// Run it incrementally, directory by directory, with a review of each diff.
export default function transform(file, api) {
  const j = api.jscodeshift;
  return j(file.source)
    .find(j.JSXOpeningElement, { name: { name: "button" } })
    .forEach((path) => { path.value.name.name = "Button"; })
    .toSource();
}

A codemod (a code transformation script) automates the mechanical part of the adoption — replacing the raw element with the system component, mapping the props, removing the inline styles — so the migration is a script run per directory with a review of the diff, not a manual find-and-replace across a thousand files. The codemod handles the 90% that is mechanical; the remaining 10% — the component that needs a prop the system does not have, the page with a layout the system does not cover — is the work that informs the system’s roadmap. Each adoption blocker is a feature the system is missing, and the roadmap is the prioritized list of those features.

Versioning and migration are the adoption problem at scale. A design system used by ten applications, each releasing on its own schedule, cannot update all of them simultaneously. Semantic versioning is the contract: a major version is a breaking change that requires consumer action, a minor is a backward-compatible feature, a patch is a fix. Ship the major with a migration guide and a codemod, deprecate the old API in the previous minor (with a console warning in development), and give the consumers a window to upgrade. A design system that breaks its consumers without warning is a system the consumers pin to an old version and never upgrade, and the version skew is worse than the breaking change. Communicate the change, provide the tool, and the consumers upgrade; surprise them, and they do not.

Conclusion

A design system is a token layer that is the single source of truth, a component layer that composes from tokens with a variant and slot API, theming as a token swap with primitive feeding semantic tokens, accessibility as a built-in property of every component, and living documentation with do/don’t guidance. Build the tokens first and everything else from them, make accessibility non-optional, document with rendered examples and judgment, and govern the lifecycle with a clear bar for inclusion. The payoff is a product that is coherent by construction, a rebrand that is a token change, and a team that builds by composition rather than reinvention.

Related Examples