Sub topic 10
Reusable components with typed variants
This chapter assumes you can write React function components with props, you know basic TypeScript (unions, keyof, Record), and you have Tailwind running in a Vite project as set up earlier. You will turn a repeated pile of utility classes into one component whose styling options are checked by the compiler.
Why extract a component
Utility classes put styling next to markup. The cost is repetition. A button might carry this class list:
<button className="rounded-md bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50">
Save
</button>Pasted into thirty places, this becomes a maintenance problem. Changing the corner radius means thirty edits, and the copies drift apart over time.
In a React project the usual fix is to extract a component, not to move the classes into a CSS file with @apply. A component gives you one place to edit the classes. It also gives you a typed props interface, so callers choose from a fixed list of options instead of writing classes by hand.
Step 1: extract the markup
Start by moving the markup and its classes into a component, with no options yet:
import type { ButtonHTMLAttributes } from 'react'
export function Button(props: ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<button
className="rounded-md bg-blue-600 px-4 py-2 font-medium text-white hover:bg-blue-700 disabled:opacity-50"
{...props}
/>
)
}ButtonHTMLAttributes<HTMLButtonElement> is the type React provides for every attribute a <button> accepts. Spreading {...props} forwards onClick, disabled, type and the rest, so the component behaves like a native button.
There is a bug waiting here. If a caller passes className, the spread comes after the className prop above it and replaces the base classes completely. Step 3 fixes this.
Step 2: add variants with a lookup table
A variant is a named style option, such as primary or danger. Do not build variants by branching on strings inside the class list. Store the full class string for each variant in an object and index into it:
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 ButtonVariant = keyof typeof variantskeyof typeof variants produces the union 'primary' | 'secondary' from the object's keys. The union and the styles come from one source, so a new key becomes a legal prop value without a second edit.
Every value is a complete class string. This is required, not stylistic. Tailwind finds classes by scanning your source for whole class names, so a lookup table of full strings is visible to it and ` bg-${color}-600 ` is not. The class-detection chapter covers the mechanism.
Step 3: several variant axes and safe overrides
Real components usually have more than one axis, such as intent (primary, danger) and size. Give each axis its own lookup table. Use Record<Union, string> so the compiler checks that every option has an entry:
import type { ButtonHTMLAttributes } from 'react'
import { cn } from './cn'
type Variant = 'primary' | 'secondary' | 'danger'
type Size = 'sm' | 'md'
const variantClasses: Record<Variant, string> = {
primary: 'bg-blue-600 text-white hover:bg-blue-700',
secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
danger: 'bg-red-600 text-white hover:bg-red-700',
}
const sizeClasses: Record<Size, string> = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-base',
}
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant
size?: Size
}
export function Button({
variant = 'primary',
size = 'md',
type = 'button',
className,
...props
}: ButtonProps) {
return (
<button
type={type}
className={cn(
'rounded-md font-medium disabled:opacity-50',
variantClasses[variant],
sizeClasses[size],
className
)}
{...props}
/>
)
}The helper imported from ./cn is the one below. The next chapter explains how it works. For now, treat it as "join these classes, and let later ones win conflicts":
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Install both packages with npm install clsx tailwind-merge.
Several details in Button matter:
- Defaults live in the destructuring.
variant = 'primary'makes the prop optional while keeping the type strict. type = 'button'. A<button>inside a form defaults tosubmit. A safe default avoids accidental form submissions. Callers can still passtype="submit".classNameis pulled out ofprops. Because it is destructured, it does not reach the spread and cannot overwrite the merged string. It is passed last tocninstead, so caller overrides win.{...props}comes last on the element. This lets callers setonClick,disabledandaria-*attributes. It is safe becauseclassNameis no longer insideprops.
Callers now get autocomplete and compile-time errors:
import { Button } from './Button'
export function Toolbar() {
return (
<div className="flex gap-2">
<Button>Save</Button>
<Button variant="secondary" size="sm">Cancel</Button>
<Button variant="danger" className="w-full">Delete</Button>
{/* <Button variant="dangerous" /> is a TypeScript error */}
</div>
)
}Because the base string has no px-* and py-* of its own, the className="w-full" override only adds width. If a caller passed px-8, twMerge would remove the conflicting px-4 from the size table instead of leaving both in the output.
Comparing ways to share styles
| Approach | Reuse | Type safety | Main drawback |
|---|---|---|---|
| Copy the class list | None | None | Copies drift apart |
| Shared constant string | Class list only | None | No props, no variants |
| `@apply` in a CSS file | Class list only | None | Moves styling away from the markup and hides what is applied |
| React component with lookup tables | Markup and styles | Variant props checked by TypeScript | You maintain the component |
For React apps, the last row is the default choice. Use @apply only for styling you cannot reach from JSX, such as markup produced by a third-party library.
Edge cases and design decisions
Boolean states are not variants. disabled, loading and selected are states. Use state variants such as disabled:opacity-50 for browser-driven states. For application state, such as a loading prop, add classes conditionally through cn, for example loading && 'cursor-wait opacity-70'.
Keep the number of variants small. Each axis multiplies the combinations you have to test visually. With three intents and two sizes you have six combinations. Add a variant only when at least two real call sites need it.
Do not extract too early. A class list used once is not a candidate. Extract when you see the same group of elements repeated, or when the component needs behavior, such as a loading state, not only styling.
Forwarding refs. In React 19, ref is an ordinary prop on function components, and ButtonHTMLAttributes combined with ref handling works through the spread. In React 18 and earlier, wrap the component in forwardRef if callers need a ref to the DOM node.
Variant libraries. Packages such as class-variance-authority formalize this lookup-table pattern and add compound variants. The hand-written version above has no dependency and is enough until you have many components with many axes. The mechanics are the same.
Polymorphism is a separate problem. If a Button must sometimes render as a link, a plain ButtonHTMLAttributes type is wrong. Make a separate LinkButton that shares the class tables, or accept an as prop with a more advanced type. Do not loosen the types until it compiles.
Exercise
You add warning: 'bg-yellow-500 text-black hover:bg-yellow-600' to variantClasses, but TypeScript reports an error in the Record<Variant, string> declaration. What is the cause, and what is the fix?
Show answer
The Variant union still lists only 'primary' | 'secondary' | 'danger', so warning is an extra key that the Record type rejects. Add 'warning' to the Variant union. The same type then lets callers write variant="warning", and the compiler will flag any other table keyed by Variant that is missing a warning entry.
Exercise
A teammate writes <Button className="px-10">Wide</Button> and finds that the button still has px-4 padding in the browser. Which part of the Button implementation is missing or wrong, and what do you check?
Show answer
The conflict is only resolved when the classes go through cn (that is, twMerge) with the caller's className last. Check that Button passes className as the final argument to cn and does not concatenate strings by hand. Also check that className is destructured out of props, so the later {...props} spread does not overwrite the merged class string.