Sub topic 2
Variants Through Props and `@apply`
Assume you know basic Tailwind utilities, CSS specificity, and React or another component framework. This chapter compares component variants with CSS reuse.
Variants Through Props
A component variant is a named style choice exposed through a prop. Keep each variant’s complete class string in a static object so Tailwind can detect the classes during its build.
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, className = "", ...props }) {
const variantClasses = variants[variant] ?? variants.primary;
return (
<button
className={`rounded-md px-4 py-2 font-semibold ${variantClasses} ${className}`}
{...props}
>
{children}
</button>
);
}Use the component like this:
<Button variant="secondary">Cancel</Button>Avoid constructing class names such as `bg-${color}-600`. Tailwind scans source text and may not generate classes that exist only after runtime interpolation.
Merging Classes and Resolving Conflicts
A caller may pass a class that conflicts with the component. String concatenation does not reliably express the intended winner. tailwind-merge removes conflicting utilities and keeps the later value.
import { twMerge } from "tailwind-merge";
const classes = twMerge(
"rounded-md px-4 py-2",
"p-3"
);
// "rounded-md p-3"Wrap this behavior in a helper when many components accept className.
Writing CSS Classes with `@apply`
@apply copies declarations from utility classes into a CSS rule. It is useful when a semantic class must be shared outside a component template.
@layer components {
.btn-primary {
@apply rounded-md bg-blue-600 px-4 py-2 font-semibold text-white;
}
.btn-primary:hover {
@apply bg-blue-700;
}
}The class can then replace the repeated utility list:
<button class="btn-primary">Save</button>Organizing Component Classes with `@layer components`
@layer components places these reusable classes between Tailwind’s base styles and utilities. A utility added directly in markup can therefore override a component class when the generated CSS order permits it.
Use components for behavior, markup, and variants. Use @apply for a stable visual pattern shared across templates. For Tailwind v4 custom utilities, prefer @utility when you need the class to participate as a first-class utility with variants.
Exercise
Which strategy fits three buttons that share markup but have different labels and variants?
Show answer
Extract a Button component, keep complete variant class strings in a static variants object, and merge caller classes with tailwind-merge when overrides are allowed.