Open three different pages of a tidy app. The buttons are the same height, the same roundness, the same colour. That isn't because the designer copied carefully. There's only one button, and it's used in three places.
One piece of UI (a button, a field, a room card) designed and coded once, then used everywhere, is a component. Its looks and states are decided from the start. A component library is the collection of those components plus their documentation (the instructions for using them). A component library is like the standard room kit at Mrs. Sri's homestay: every room gets the same reading lamp, the same key tag and the same "Do not disturb" sign. The sign has two sides and the lamp comes in two sizes, like a component with a few choices of look. If Mrs. Sri changes the key tag design, she changes the kit list once, and all the rooms follow. If every room bought its own things, a year later no two rooms would match.
One source, many uses
The Attic and Garden room cards were once copied from the Terrace room card, then changed a little. Today Mrs. Sri raises the height of the button on the Terrace card from 40px to 48px. How many of the three "Choose" buttons are 48px now? Guess first.
Here are three room cards made by copying. We measured the height of their buttons in Chromium, WebKit and Firefox with getBoundingClientRect() (a JavaScript command that reads an element's size). The result was the same in all three:
| Card | Where it came from | Button height | Anything else |
|---|---|---|---|
| Terrace Room | the one Mrs. Sri just changed | 48px | |
| Attic Room | a copy, border: 0 |
38px | its green is #16803d, a typo |
| Garden Room | a copy, padding: 8px |
42px | fully booked, but its button stays green because the copy has no :disabled style (the look of a disabled button) |
So the answer to the guess: only one. A copy doesn't change when the original changes, so each copy slowly becomes more different from the original. This is called drift (slowly moving away).
A component turns this around: not many copies, but one source used in many places. In plain JavaScript, a component can be a function that takes data and returns markup (HTML code) as text. In this code, the function roomCard makes one room card, then innerHTML puts all three cards into #rooms:
<div class="rooms" id="rooms"></div>
<script>
function roomCard({ name, price, guests, status = "available" }) {
const priceText = price.toLocaleString("en-US", { style: "currency", currency: "USD" }); // 35 becomes "$35.00"
let action = `<button type="button" class="btn btn--primary btn--lg">Choose ${name}</button>`;
if (status === "full") action = `<button type="button" class="btn btn--secondary btn--lg" disabled>Full on 12 Dec</button>`;
return `<article class="room-card room-card--${status}">
<h2>${name}</h2>
<p>${priceText} / night · ${guests} guests</p>
${action}
</article>`;
}
document.querySelector("#rooms").innerHTML = [
roomCard({ name: "Terrace Room", price: 35, guests: 2 }),
roomCard({ name: "Attic Room", price: 27.5, guests: 2 }),
roomCard({ name: "Garden Room", price: 42.5, guests: 4, status: "full" }),
].join("");
</script>
roomCardis called three times with different data. The object{ name, price, guests, status }(one room's data) is the props: the component's inputs. Inside the HTML text,${name}is replaced by the value ofname, such as "Terrace Room". In React (a JavaScript library for building UI), a function like this is actually called a component, and its object is called props.status = "available"is a default value: if the status is left out, the room is available. The Garden Room getsstatus: "full", so its button is replaced by a disabled "Full on 12 Dec" button.btn--lg(the class for a large button) is written only in this function. Change it in this one place, and all three buttons change. Measured: 48, 48, 48px.- Be careful once
namecomes from a form, for example a room name someone types.innerHTMLreads it as HTML. So if someone types the name<img src=x onerror="...">, the imagexfails to load, and the code insideonerror(code for when an image fails to load) runs on the page (we tried it in Chromium). This attack is called XSS: code slipped in through data that the page shows. For data from users, create the element withdocument.createElement, then fill it withtextContent, which always shows its content as plain text. You can also use React or Vue (another JavaScript library), which show{name}(React) and{{ name }}(Vue) as plain text.
Anatomy: variants, states, sizes, props
Every component in a library needs four things: variants (its versions of the look), states (how it is while in use), sizes, and props (the inputs that the people who use the component may set). Here are the three components of Mrs. Sri's page:
Button .btn |
Field .field |
Room card .room-card |
|
|---|---|---|---|
| Variants | primary, secondary, ghost | text, tel, email | available, selected, full |
| Sizes | sm 32px, md 40px, lg 48px | one: 44px | compact, with photo |
| States | default, hover, active, focus-visible, disabled, loading | default, focus, invalid, disabled | loading (skeleton), default, photo failed to load |
| Props | label, variant, size, disabled, busy | label, type, help, error, disabled | name, price, guests, status |
A component's API is the way you use it from outside. In plain HTML and CSS, the button component's API is its classes and attributes:
.btn { padding: 7px 16px; font: inherit; font-weight: 600; line-height: 24px; border: 1px solid transparent; border-radius: var(--radius-md); }
.btn--sm { padding: 3px 12px; font-size: 14px; } /* 32px */
.btn--lg { padding: 11px 16px; } /* 48px */
.btn--primary { color: var(--on-action); background: var(--action); }
.btn--secondary { color: var(--action); background: var(--surface-card); border-color: var(--action); }
.btn--ghost { color: var(--action); background: transparent; }
.btn:focus-visible { outline: 3px solid var(--text); outline-offset: 2px; }
.btn:disabled { color: var(--text-muted); background: var(--border); border-color: var(--border); cursor: not-allowed; }
.btn[aria-busy="true"] { cursor: progress; }
.btnholds everything every button shares. Other classes such as.btn--primaryand.btn--lgonly add what differs: those are the variants and sizes.- Height = top padding +
line-height+ bottom padding + the top and bottom border: 3 + 24 + 3 + 2 = 32, 7 + 24 + 7 + 2 = 40, 11 + 24 + 11 + 2 = 48px. - States are written with pseudo-classes (the part of a selector that starts with a colon and applies in a certain state, such as
:focus-visibleand:disabled) and with attributes (aria-busy). So the people who use the component don't have to remember extra classes. - The colours come from the design tokens of the previous lesson, so the dark theme reaches the button without changing
.btn.
Documenting a component
A component without documentation gets used the wrong way, or copied again. One documentation page holds:
- Purpose: when to use it, when not to. "Room cards for the list of rooms; not for a booking summary."
- Variants, sizes and states, each with an example you can see.
- A props table, like this one for
roomCard(string = text, number = a number):
| Prop | Type | Default | Note |
|---|---|---|---|
name |
string | required | may be long: the title wraps to a new line |
price |
number | required | per night: 35 is written "$35.00" |
guests |
number | required | the most guests |
status |
"available", "selected", "full" | "available" | full: a disabled button and the next free date |
- Accessibility notes: the button label names the room ("Choose Terrace Room"), so a screen reader user can tell the three buttons apart.
- Example code to copy.
Many teams write this documentation in Storybook, a tool that calls itself "a frontend workshop for building UI components and pages in isolation" (separately from the app). In Storybook, each story shows one state of a component, for example a primary button in size lg that is loading, or a tel field whose content is wrong (invalid). The Lab on this page works the same way.
Use a library or build your own
There are three kinds to choose from. A headless library is a library with no look: it holds only behaviour.
| Kind | Examples | What you get | What you do |
|---|---|---|---|
| Full library | Material UI, Ant Design | a finished look and behaviour | adapting it to the brand, often fighting its default styles |
| Headless library | Radix Primitives, React Aria, Headless UI | behaviour: keyboard, focus, ARIA attributes | all of the CSS |
| Code copied into the project | shadcn/ui | component code dropped into your project folder by npx shadcn@latest add button |
maintaining that code yourself |
shadcn/ui says of itself: "This is not a component library. It is how you build your component library." The code becomes yours.
How to choose for Mrs. Sri's site:
- Built-in HTML elements first. The button, the field and the card need only her own HTML and CSS.
<button>already takes focus and can be pressed with Enter and Space.<dialog>opened withshowModal()already handles focus and the Esc key. - Borrow complex behaviour. A calendar for choosing the check-in and check-out dates is different. The WAI-ARIA Authoring Practices Guide (the W3C's guide for building accessible components) has a date picker example (a calendar for picking dates). That example lists 11 rows of keyboard keys for its date grid alone: arrows in four directions, Home, End, Page Up, Shift + Page Up, and so on. A headless library gives that behaviour, and the look stays Mrs. Sri's.
- A full library suits internal tools (tools only the owner and her team use) whose look doesn't have to be distinct, such as an admin dashboard with dozens of tables.
⚠️ How a library slowly falls apart
- Copying instead of reusing. Copies become more and more different from the original: buttons at 48, 38, 42px, and a
#16803dgreen. - Exploding variants.
.btn-green-big-round-2is made for every new need. Add a variant only when its job really differs, like.btn--dangerfor "Cancel booking". - A prop that's too free.
color="#16a34a"lets every user of the component pick their own colour, so drift comes back, this time through the component itself. - Designing only the default state. A component isn't finished until its hover, focus-visible, disabled and loading states exist.
- A library for everything, then
!importanteverywhere.!importantis a CSS mark that forces one rule to win. If you keep using it to fight a full library's default styles, you may need a headless library instead.
TL;DR: A component is one piece of UI made once and used everywhere. A component library is the collection of those components plus their documentation. Hand-made copies slowly become different from the original (drift: buttons at 48, 38, 42px). With a component, one change reaches every use. Every component has four things, for example on a button: variants (versions of the look: primary, secondary, ghost), states (default, hover, active, focus-visible, disabled, loading), sizes (sm 32, md 40, lg 48px) and props (its inputs; on the room card: name, price, guests, status). Document the purpose, variants and states, a props table, accessibility notes and example code, for instance in Storybook (a tool for documenting components, one story = one state). Use built-in HTML elements first (<button>, <dialog>). For complex behaviour such as a date picker (a calendar for picking dates), use a headless library, which gives behaviour with no look (Radix Primitives, React Aria, Headless UI). A full library (Material UI, Ant Design) suits internal tools, and shadcn/ui (component code copied into your project) suits you if you want the component code to be yours.
⚡ Copies drift apart
Guess first: the Attic and Garden cards were copied from the Terrace card. Today the height of the Terrace card's button goes from 40px to 48px. How many of the three "Choose" buttons are 48px now?
Only one. The others are 38px and 42px, because a copy doesn't change when the original changes. This is called drift: copies slowly become different from the original.
Meaning: A component (one piece of UI made once, then used everywhere) turns this problem around: one source, many uses. A change at the source reaches every use.
⚡ One function, three cards
Write:
function roomCard({ name, price, guests, status = "available" }) {
const priceText = price.toLocaleString("en-US", { style: "currency", currency: "USD" }); // 35 becomes "$35.00"
return `<article class="room-card room-card--${status}">
<h2>${name}</h2>
<p>${priceText} / night · ${guests} guests</p>
</article>`;
}
Meaning: roomCard is a room card component written as a JavaScript function. The function takes one room's data and returns the HTML code of its card, with ${name} replaced by the room's name. The object { name, price, guests, status } is the props, the component's inputs. When the function is called three times with three rooms' data, one change here reaches all three cards.
⚡ Four things in every component
Meaning: Every component in a library needs four things, for example on a button: variants (versions of the look: primary, secondary, ghost), states (default, hover, active, focus-visible, disabled, loading), sizes (sm 32, md 40, lg 48px) and props (inputs). Document them all, for instance in Storybook (a tool for documenting components), one story per state.