Sub topic 3
Conditional and Dynamic Class Names
Assume you know React props and JSX, basic TypeScript, and how Tailwind is configured in Vite.
Conditional and dynamic class names
Tailwind scans source files for complete class names. Do not build a class from fragments. The scanner may not detect text-${color}-600.
Map each possible value to a complete class:
const colorClasses = {
red: "text-red-600",
green: "text-green-600",
} as const
export function Status({ color }: { color: keyof typeof colorClasses }) {
return <p className={colorClasses[color]}>Ready</p>
}Use ordinary JavaScript conditions for boolean styles:
<button className={`rounded px-4 py-2 ${active ? "bg-blue-600 text-white" : "bg-gray-100 text-gray-900"}`}>
Select
</button>Reusable components with typed variants
A variant is a named styling choice, such as primary or secondary. Type the variant so callers cannot pass unsupported values.
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={`rounded-md px-4 py-2 font-medium ${variants[variant]} ${className ?? ""}`}
{...props}
/>
)
}Merging and overriding classes safely
String interpolation can leave conflicting utilities, such as both p-2 and p-4. clsx joins conditional values. tailwind-merge removes conflicting Tailwind utilities.
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Use cn(baseClasses, variants[variant], className) in reusable components. Put caller overrides last.
> callout tip > Keep dynamic values in lookup tables. This preserves Tailwind's build-time class detection.
Customizing the theme
Add shared design tokens in your CSS:
@import "tailwindcss";
@theme {
--color-brand-500: #3b82f6;
--font-display: "Inter", sans-serif;
}This creates utilities such as bg-brand-500 and font-display.
Arbitrary values and editor support
Use bracket syntax for a genuine one-off value:
<div className="w-[320px] bg-[#1da1f2]">Promo</div>Prefer theme tokens for repeated values. Install Tailwind CSS IntelliSense for class completion and diagnostics. Enable the official class-sorting formatter so utility lists stay consistent.
Exercise
Why might text-${color}-600 fail, and what should replace it?
Show answer
Tailwind may not detect the assembled class. Map each allowed color to a complete string, such as text-red-600.