Sub topic 5
Variants through props
This chapter assumes you can read basic React (props, JSX, template literals) and know Tailwind utilities such as px-4 and hover:bg-blue-700. It also assumes you have already extracted a repeated button into a single component. Here you will make that component produce several visual versions of itself, called variants, and you will see why the way you write the class names matters.
What a variant prop is
A variant prop is a component input that selects one of several predefined looks. The caller writes <Button variant="secondary">. The component decides which Tailwind classes that name stands for. Callers describe intent ("secondary") and never repeat class lists.
This keeps one decision in one place. If the brand's primary blue changes, you edit the component once instead of every call site.
The basic pattern: a lookup object
The simplest approach holds the shared classes once and maps each variant name to a complete class string.
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>
);
}Reading it from top to bottom:
variantsis a plain object. Each key is a variant name and each value is a full string of utilities.variant = "primary"gives the prop a default, so<Button>Save</Button>still works....propscollects every other prop (onClick,type,disabled) and passes it to the<button>. Without this, the component would silently drop them.- The template literal joins the shared classes (
rounded-md px-4 py-2 font-semibold) with the variant classes.
Usage looks like this:
<Button>Save</Button>
<Button variant="secondary">Cancel</Button>Why complete class strings matter
Tailwind does not run your JavaScript. It scans your source files as plain text, looks for tokens that resemble class names, and generates CSS only for the tokens it finds. If a class name never appears as a whole token in a scanned file, no CSS is generated for it, and the element renders unstyled.
This is why the lookup object stores full strings such as "bg-blue-600 text-white hover:bg-blue-700". Each class is present in the source exactly as written, so the scanner finds it.
The most common mistake is building class names from pieces:
// Broken: Tailwind never sees "bg-red-600" or "bg-green-600" as whole tokens.
function Badge({ color, children }) {
return <span className={`bg-${color}-600 px-2 text-white`}>{children}</span>;
}The source contains bg-${color}-600, which is not a class. At build time Tailwind cannot know that color will be "red". The page works for any class that happens to appear elsewhere in your code, which makes the bug intermittent and confusing. In development you may see the color on one screen and not on another.
The fix is to write the full names somewhere the scanner can read them:
const colors = {
red: "bg-red-600",
green: "bg-green-600",
};
function Badge({ color = "red", children }) {
return <span className={`${colors[color]} px-2 text-white`}>{children}</span>;
}The same rule applies to values that arrive from props, state, or an API. If the set of possible values is open-ended (for example, a color chosen by a user), a class is the wrong tool. Use an inline style attribute for that single value, or a CSS variable set through style and read by an arbitrary-value utility such as bg-[var(--brand)].
How the pieces flow
The diagram shows what happens at build time and at render time. The scanner reads the source once. The component picks a string at runtime from the strings the scanner already saw.
Handling invalid and missing variants
With the lookup pattern, an unknown variant name returns undefined. The template literal then inserts the text undefined into the class list. Nothing crashes, and the button just looks unstyled except for the shared classes. That is easy to miss.
There are three reasonable responses:
- Fall back to a default:
variants[variant] ?? variants.primary. - Throw or warn in development so mistakes surface early.
- Use TypeScript so that invalid names fail at compile time.
A TypeScript version of the component:
import type { ButtonHTMLAttributes } from "react";
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
danger: "bg-red-600 text-white hover:bg-red-700",
} as const;
type Variant = keyof typeof variants;
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant;
};
export function Button({ variant = "primary", className = "", ...props }: ButtonProps) {
return (
<button
className={`rounded-md px-4 py-2 font-semibold ${variants[variant]} ${className}`}
{...props}
/>
);
}keyof typeof variants derives the allowed names from the object, so adding a danger entry automatically makes variant="danger" valid and variant="dagner" a compile error. The className prop is also accepted here, which leads to the next topic.
Multiple dimensions: variant, size, and state
Real components usually vary along more than one axis. Keep one lookup object per axis rather than one object with every combination.
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
};
const sizes = {
sm: "px-3 py-1 text-sm",
md: "px-4 py-2 text-base",
lg: "px-6 py-3 text-lg",
};
export function Button({
variant = "primary",
size = "md",
children,
...props
}) {
const classes = [
"rounded-md font-semibold",
"disabled:cursor-not-allowed disabled:opacity-50",
variants[variant],
sizes[size],
].join(" ");
return (
<button className={classes} {...props}>
{children}
</button>
);
}Two variant axes with three and two options produce six combinations, but you write only five entries. Add a third axis and the saving grows. Putting the classes in an array and joining them keeps each concern on its own line and avoids stray double spaces from empty values.
Note that disabled: is itself a Tailwind variant. It styles the element based on its disabled attribute, so you do not need a separate disabled prop to change the appearance. Passing disabled through ...props is enough.
Variant props versus Tailwind variants
The word "variant" means two things here, and mixing them up causes confusion.
| Term | Where it lives | Example | What decides it |
|---|---|---|---|
| Component variant | Your component's props | `variant="secondary"` | The caller, in JSX |
| Tailwind variant | A prefix on a utility | `hover:bg-blue-700`, `md:px-6` | The browser state or viewport |
A component variant chooses which class strings are used. A Tailwind variant makes one class conditional on state or screen size. Component variant strings often contain Tailwind variants, as hover:bg-blue-700 does inside primary.
Do not try to replace responsive behavior with a prop when a Tailwind variant would do. A size prop is right when the caller wants a larger button. The md: prefix is right when the same button should grow on wide screens.
Overriding variant classes from outside
Callers sometimes need a one-off adjustment, such as extra margin or a wider button. The usual approach is to accept a className prop and append it, as the TypeScript example above does.
Appending has a catch. If the base component has px-4 and the caller passes px-8, both classes land on the element. Tailwind generates its utilities in one stylesheet, and when two utilities set the same property, the one defined later in the stylesheet wins. It is not the one that appears later in the class attribute. So px-4 px-8 and px-8 px-4 behave the same, and the winner depends on Tailwind's internal ordering, not on your intent.
For layout-neutral additions such as mt-4 or w-full, appending is safe because nothing conflicts. For true overrides, you need a merge step, which the next chapter covers using tailwind-merge. As a preview, it removes the conflicting earlier class so the later one is the only one left:
import { twMerge } from "tailwind-merge";
twMerge("px-2 py-1", "p-3"); // "p-3"In the meantime, a defensible rule is to let callers add classes but not to promise that they can override existing ones.
Checking your work
When a variant looks wrong, work through these checks in order:
- Inspect the element in browser developer tools. Is the expected class present in the
classattribute? - If the class is present but has no effect, search the generated CSS for it. If it is missing there, the scanner never saw a complete token.
- If the class is absent, the lookup returned
undefinedor the wrong key. Log thevariantvalue. - If two classes set the same property, remember that stylesheet order decides, and consider a merge helper.
Trade-offs of the props approach
Variant props work well, but they have costs.
- The class names live in JavaScript, so they are no longer greppable as plain HTML. You search for the component instead.
- Every variant name you expose becomes API. Adding
variant="ghost"is easy. Removing it later breaks callers. - A component with five axes and many options turns into its own small design system. When that happens, consider a library built for this job, such as class-variance-authority, rather than growing the lookup objects by hand.
- The pattern depends on your framework. The same idea works in Vue with a computed class and in Svelte with a lookup in the script block, but the syntax changes. The rule about complete class strings stays the same everywhere.
Exercise
A teammate writes <span className={text-${tone}-700 font-medium}> where tone is "red" or "green". In production, the text sometimes has no color. Explain why, and rewrite the component so it works.
Show answer
Tailwind scans the source as text and never runs the JavaScript, so it sees the fragment text-${tone}-700, not text-red-700 or text-green-700. If those full class names appear nowhere else in the scanned files, no CSS is generated for them, and the color is missing. The fix is to map each allowed value to a complete class string: const tones = { red: "text-red-700", green: "text-green-700" }; and then write <span className={${tones[tone]} font-medium}>. Now both full class names exist in the source and the scanner finds them.
Exercise
Add a size prop with sm and lg options to the two-variant Button shown earlier in the chapter. What should the lookup objects look like, and what happens if a caller passes size="xl"?
Show answer
Create a second object, for example const sizes = { sm: "px-3 py-1 text-sm", lg: "px-6 py-3 text-lg" };, and add sizes[size] to the class list with a default such as size = "sm". Remove px-4 py-2 from the shared classes so they do not conflict with the size classes. Passing size="xl" returns undefined, so the string undefined ends up in the class list and the button has no padding or text size. Guard against it with a fallback such as sizes[size] ?? sizes.sm, or use TypeScript with keyof typeof sizes so the mistake fails at compile time.