Sub topic 4
Extracting a component
This chapter assumes you know Tailwind utility classes such as px-4 and bg-blue-600. It also assumes you have used a component framework such as React, or template partials. The examples use React. The same steps work in Vue, Svelte, or a server-side partial.
Why extract
The earlier chapters showed how utility classes produce long class attributes. Here is the same button written three times:
<button class="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700">Save</button>
<button class="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700">Publish</button>
<button class="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700">Send</button>To change the button color, you must edit three places. If you miss one, the interface becomes inconsistent. The long class list is not the problem. The problem is that one design decision lives in several places.
CSS can't fix this well. A CSS class would only move the repetition from the markup into the stylesheet. A component solves it where the repetition happens, in the template. It stores the markup and its classes once and lets you reuse them by name.
The basic extraction
Extraction has three steps:
- Find the markup that repeats, with the same structure and the same classes.
- Move it into a component, and keep the classes as a literal string.
- Replace the parts that differ with props or children.
For the buttons, the label is the only part that differs. React passes content placed between the tags as children:
export function Button({ children, ...props }) {
return (
<button
className="rounded-md bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
{...props}
>
{children}
</button>
);
}
export function Toolbar() {
return (
<div className="flex gap-2">
<Button>Save</Button>
<Button>Publish</Button>
<Button type="submit">Send</Button>
</div>
);
}The class list now exists in one place. Changing bg-blue-600 to bg-indigo-600 updates every button.
The ...props spread matters. It forwards attributes such as type, onClick, disabled, and aria-label to the real <button>. Without it, your component quietly drops them, and you would have to add each attribute by hand as you need it.
What belongs inside the component
Not every shared class belongs in a component. Keep the classes that define what the element is, and leave out the ones that describe where it sits.
| Inside the component | Outside, at the call site |
|---|---|
| Padding, font weight, radius, colors | Margin such as `mt-4` or `ml-auto` |
| Hover, focus, and disabled styles | Grid or flex placement such as `col-span-2` |
| Transitions and focus rings | Width set by the parent layout, such as `w-1/2` |
Margins and placement belong to the parent's layout. If a button carries mt-4 inside the component, it will have the wrong spacing in every place that doesn't want it. The parent should control spacing, for example with gap-2 on a flex container as in Toolbar above, or by adding a class when it renders the component.
Variants through props
Real interfaces have more than one kind of button. Add a variant prop that selects between complete class strings:
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
};
export function Button({ variant = "primary", children, ...props }) {
return (
<button
className={`rounded-md px-4 py-2 font-semibold ${variants[variant]}`}
{...props}
>
{children}
</button>
);
}The shared classes appear once, in the template string. Each variant's classes appear once, in the variants object. A call looks like <Button variant="secondary">Cancel</Button>.
If variant is omitted, the default "primary" applies. If a caller passes an unknown name such as "danger", variants["danger"] is undefined, and the string undefined ends up in the class attribute. That does not crash, but the button gets no color. TypeScript catches this at compile time. In plain JavaScript, you can throw an error or fall back to the default.
The rule for class detection
Tailwind does not run your code. It scans your source files as plain text and looks for strings that match class names. It generates CSS only for the classes it finds. This leads to the most common error in component extraction.
This version does not work:
// Broken: Tailwind never sees "bg-red-600" or "bg-green-600" spelled out
export function Badge({ color, children }) {
return (
<span className={`rounded px-2 py-1 text-white bg-${color}-600`}>
{children}
</span>
);
}The source text contains bg-${color}-600, which is not a class name. No CSS is generated for bg-red-600, even if a caller passes "red". In development, you might see the style appear if another file happens to use the class. That makes the bug appear and disappear.
This version works:
const colors = {
red: "bg-red-600",
green: "bg-green-600",
};
export function Badge({ color = "red", children }) {
return (
<span className={`rounded px-2 py-1 text-white ${colors[color]}`}>
{children}
</span>
);
}Every class name is written out in full somewhere in the source, so the scanner finds it. The rule is that class names must exist as complete strings. You can choose between them at runtime, but you cannot build them from parts.
Letting callers add classes
Callers sometimes need a small adjustment, such as a margin or a width. A common pattern is to accept a className prop and append it:
export function Button({ className = "", children, ...props }) {
return (
<button
className={`rounded-md bg-blue-600 px-4 py-2 font-semibold text-white ${className}`}
{...props}
>
{children}
</button>
);
}Now <Button className="w-full">Save</Button> adds w-full. Note that className is destructured separately. If it stayed inside ...props, the later spread would replace the component's own className and remove all of its styles.
This pattern works for classes that don't conflict, such as w-full or mt-4. It fails when a caller tries to override a class the component already sets:
<Button className="bg-red-600">Delete</Button>The element now has both bg-blue-600 and bg-red-600. The order of the classes in the attribute does not decide which wins. Tailwind's generated stylesheet decides, and in that sheet the two rules have equal specificity, so whichever appears later in the sheet wins. You cannot predict that from your template. The next chapters cover how tailwind-merge resolves these conflicts. For now, treat overrides of the same property as a signal to add a variant instead.
Common mistakes
- Extracting too early. Two similar elements are not yet a pattern. Wait until you see the same thing three times, or until you know the design will change as a unit.
- Extracting too much. A
Cardthat takes 15 props to cover every case is harder to read than a few plain elements. When a component needs many props, split it into smaller pieces, such asCard,CardHeader, andCardBody. - Dropping attributes. Forgetting
...propsmeansonClick,type, and accessibility attributes silently disappear. - Using the wrong element. A component that always renders a
<button>is wrong for a link that looks like a button. Accept anasprop or create a second component, so you don't render clickable<div>elements. - Hiding utility classes in many layers. If a component only wraps another component and adds one class, a reader must open three files to see the real styling. Keep the layers shallow.
When a component is not available
Components only help where your template language supports them. If you write plain HTML, or a templating system with only loops and includes, a partial (a reusable template fragment) does the same job. The same rules apply: keep full class names in the source and pass in the parts that vary. When the repetition is not in your templates at all, because the markup comes from a CMS or a Markdown renderer, you can't wrap it in a component. That case is where @apply, covered in later chapters, becomes useful.
Exercise
A teammate writes <span className={bg-${tone}-100 text-${tone}-800}> inside an Alert component and calls it with tone="yellow". The yellow styles are missing in the production build. What is wrong, and how do you fix it?
Show answer
Tailwind scans source files as plain text and never evaluates the template string, so bg-yellow-100 and text-yellow-800 do not appear in the source and no CSS is generated for them. Fix it by mapping each tone to complete class strings, for example const tones = { yellow: "bg-yellow-100 text-yellow-800", red: "bg-red-100 text-red-800" };, and using ${tones[tone]} in the component.
Exercise
A Button component spreads {...props} after its own className="rounded-md bg-blue-600 ..." and a caller passes className="w-full". Why do the button's blue background and padding disappear?
Show answer
The spread comes later in the JSX, so the caller's className replaces the component's own className instead of adding to it. Destructure className as its own prop, then build the final string yourself, for example ` rounded-md bg-blue-600 px-4 py-2 ${className} `, and spread only the remaining props.