Sub topic 10
Reusable components with typed variants
Long class lists repeat quickly. A button used in twenty places should not carry the same 120 characters of classes twenty times. In React, the fix is a component, not a CSS abstraction. This chapter shows how to extract a component and give it variants that TypeScript can check.
This chapter assumes you can write React components with props and JSX, and that you have Tailwind running in a Vite project as set up earlier. It also assumes you know basic TypeScript types.
Extract a component, not a class
Tailwind works best when the repeated markup lives in one place. If you see the same group of utility classes in several files, move the element into a component. Callers then use <Button> and never see the classes.
This keeps Tailwind's main benefit. Styles stay next to the markup they affect, and you edit them in one file.
Model variants as a lookup table
A variant is a named style choice, such as primary or secondary. Avoid long ternary chains in the class string. Use an object that maps each variant name to its full class string.
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
} as constTwo details matter here:
- Each value is a complete string, so Tailwind can detect every class when it scans your source.
as constkeeps the keys as literal types. That letskeyof typeof variantsproduce the union'primary' | 'secondary'.
Type the props from the table
Derive the prop type from the object. When you add a variant to the table, the type updates by itself.
import { cn } from './cn'
const variants = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
} as const
type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: keyof typeof variants
}
export function Button({ variant = 'primary', className, ...props }: ButtonProps) {
return (
<button
className={cn(
'rounded-md px-4 py-2 font-medium disabled:opacity-50',
variants[variant],
className
)}
{...props}
/>
)
}The component does four things:
- It extends the native button attributes, so
onClick,typeanddisabledwork as usual. - It adds an optional
variantprop, restricted to the table keys. - It sets
primaryas the default. - It combines base classes, variant classes and the caller's
classNamewithcn.
The cn helper comes from the previous chapter's tools: clsx joins conditional values and tailwind-merge resolves conflicts. It is last in the chain on purpose. A caller can write <Button className="px-8"> and the px-8 wins over the base px-4.
Using the component
TypeScript now checks every call site.
export function Actions() {
return (
<div className="flex gap-2">
<Button>Save</Button>
<Button variant="secondary" className="px-8">
Cancel
</Button>
{/* Type error: "danger" is not a key of variants */}
{/* <Button variant="danger">Delete</Button> */}
</div>
)
}A typo such as variant="primry" fails at compile time, and editors autocomplete the valid names.
Common errors
- Building class names from fragments. Writing `
bg-${color}-600` hides the full class from Tailwind, so no CSS is generated. Keep full strings in the table. - Putting
classNamebefore the variant incn. The base or variant classes then override the caller's. Put the caller's value last. - Forgetting
...props. Without spreading the rest props,onClickanddisabledare silently dropped. - Extracting too early. Wait until a pattern repeats. A single-use element does not need a component.
Exercise
You add danger: 'bg-red-600 text-white hover:bg-red-700' to the variants object. Do you need to change the ButtonProps type, and why does className="bg-black" passed by a caller override the variant background?
Show answer
No, ButtonProps uses keyof typeof variants, so 'danger' becomes a valid variant automatically. The caller's className is passed last to cn, and tailwind-merge removes the earlier conflicting bg-red-600 (or other variant background) in favor of bg-black.