Sub topic 9
Conditional and dynamic class names
This chapter assumes you have read the chapters on setup and state variants. You should also be comfortable with React props, template literals, and TypeScript object types.
Tailwind builds its CSS before your app runs. React decides which classes to apply while the app runs. Most bugs in this area come from that gap. This chapter shows how to write class names that depend on props or state and still end up in the generated stylesheet.
Why interpolated class names fail
Tailwind does not execute your code. It reads your source files as plain text, looks for strings that resemble class names, and generates CSS for each one that matches a utility. The previous chapter covered this scan in detail.
Look at this component:
type StatusProps = { color: 'red' | 'green' }
export function Status({ color }: StatusProps) {
return <p className={`text-${color}-600`}>Status</p>
}The source text contains text-, -600, and a placeholder. It never contains text-red-600 or text-green-600. Tailwind generates no rule for either one. The element gets a class that matches nothing, and the text stays its default color. There is no build error, which is why this bug is easy to miss.
The same problem appears when you build names with string concatenation ('bg-' + tone + '-500'), with .replace(), or with padding-${size}.
The rule: write every class in full
Keep each class name intact somewhere in your source as one contiguous string. The scan does not care where it appears. It can be in a JSX attribute, an object value, an array, or a constant.
The standard fix is a lookup object that maps each input value to a complete class string:
type StatusProps = { color: 'red' | 'green' }
const colorClasses = {
red: 'text-red-600',
green: 'text-green-600',
} as const satisfies Record<StatusProps['color'], string>
export function Status({ color }: StatusProps) {
return <p className={colorClasses[color]}>Status</p>
}Two details make this pattern safer:
satisfies Record<...>makes TypeScript report an error if you add a new value to thecolorunion and forget to add its class.as constkeeps the string literals narrow, which helps editor tooling.
A lookup also keeps your design choices in one place. A reviewer can see every color that Status can produce without tracing string logic.
Simple conditionals
For a single on/off choice, a ternary with two complete strings is enough:
export function Tab({ active, label }: { active: boolean; label: string }) {
return (
<button
className={
active
? 'border-b-2 border-blue-600 px-3 py-2 text-blue-600'
: 'border-b-2 border-transparent px-3 py-2 text-gray-600 hover:text-gray-900'
}
>
{label}
</button>
)
}This works, but the shared classes (border-b-2 px-3 py-2) are repeated in both branches. Repetition invites drift. When one branch gets edited and the other does not, the two states stop lining up. Separate the always-applied classes from the conditional ones.
Joining classes with clsx
The cn helper from the spine wraps clsx and tailwind-merge. Here is the same helper, shown again so this chapter runs on its own:
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}clsx accepts strings, arrays, and objects. In an object, a key is included when its value is truthy. Falsy values such as false, null, and undefined are skipped, so you can write inline conditions without building empty strings:
import { cn } from './cn'
type TabProps = { active: boolean; disabled?: boolean; label: string }
export function Tab({ active, disabled, label }: TabProps) {
return (
<button
disabled={disabled}
className={cn(
'border-b-2 px-3 py-2',
active ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-600',
{ 'cursor-not-allowed opacity-50': disabled }
)}
>
{label}
</button>
)
}Every class here is a complete string literal, so the scan finds all of them. The shared classes appear once.
Avoid the condition && 'class' form with values that can be 0 or an empty string. In React, 0 && 'x' evaluates to 0, which clsx treats as falsy, so it is safe inside clsx. It is not safe when you render the value as a child. Keep that distinction in mind.
Letting the DOM carry the state
Sometimes you do not need JavaScript to choose the class. If you put the state on the element as a data-* or aria-* attribute, Tailwind variants can style it directly:
export function Tab({ active, label }: { active: boolean; label: string }) {
return (
<button
role="tab"
aria-selected={active}
data-active={active}
className="border-b-2 border-transparent px-3 py-2 text-gray-600 data-[active=true]:border-blue-600 data-[active=true]:text-blue-600"
>
{label}
</button>
)
}React renders data-active={true} as the string "true", so the selector data-[active=true] matches. This approach has three advantages:
- The class list is static, which removes any chance of the scan missing a class.
- The
aria-selectedattribute doubles as accessibility information. You can style with thearia-selected:variant instead. - Parent elements can style children by state with
group-data-[active=true]:.
The trade-off is that the state now lives in the markup. Tests and browser tools will see those attributes, which is usually a benefit.
Truly dynamic values: CSS variables
A lookup works when the set of values is finite. It cannot work when a value comes from data, such as a progress percentage, a user-chosen color, or a measured width. You cannot list every possible number as a class.
For these cases, pass the value through a CSS custom property set with the style prop, and let a static class read it:
import type { CSSProperties } from 'react'
export function ProgressBar({ percent }: { percent: number }) {
const clamped = Math.min(100, Math.max(0, percent))
const style = { '--progress': `${clamped}%` } as CSSProperties
return (
<div className="h-2 w-48 rounded bg-gray-200">
<div style={style} className="h-2 w-(--progress) rounded bg-blue-600" />
</div>
)
}The class w-(--progress) is a complete, static string. In Tailwind v4 it is shorthand for w-[var(--progress)]. The number changes at runtime, but the class name never does.
Clamp or validate any value that comes from outside. The value goes into a style declaration, so a bad input should not produce invalid CSS.
Safelisting classes that never appear in source
Sometimes class names come from outside your code, for example from a CMS or an API response. The scan never sees them. Tailwind v4.1 and later lets you register them in your stylesheet with @source inline():
@import "tailwindcss";
@source inline("bg-{red,green,blue}-500");Brace expansion in the pattern produces bg-red-500, bg-green-500, and bg-blue-500. Tailwind generates all three whether or not they appear in your files. Use this sparingly. Each safelisted class adds CSS to every user's download, so a lookup object is better whenever you control the values.
Choosing a technique
| Situation | Technique | Reason |
|---|---|---|
| One of a few known values | Lookup object | Complete strings, type-checked |
| On/off toggle | `cn()` with a conditional | Shared classes written once |
| State already in the DOM | `data-*` or `aria-*` variants | Static class list |
| Number or color from data | CSS variable plus `style` | Cannot be enumerated |
| Classes from outside the source | `@source inline()` | Forces generation |
Common mistakes
- Building a class from a prop with a template literal.
- Splitting a class across two strings and joining them, such as
'bg-' + 'red-500'. - Putting classes in a file outside the scanned paths. Tailwind v4 detects sources automatically and skips files in
.gitignore. A package innode_modulesis not scanned unless you add it with@source. - Expecting later classes to win. Which of two conflicting utilities applies depends on their order in the generated CSS, not on their order in the
classNamestring. The next chapters cover howtailwind-mergeaddresses this.
Exercise
A teammate writes <span className={bg-${tone}-100 text-${tone}-800}> where tone is 'amber' or 'sky'. The badge has no colors in production. Explain why, then rewrite it so that it works and so TypeScript flags a missing tone.
Show answer
Tailwind scans source text and never runs the template literal, so bg-amber-100, text-amber-800, and the sky equivalents never appear in full. No CSS is generated for them. Fix it with a lookup object of complete strings:
const toneClasses = {
amber: 'bg-amber-100 text-amber-800',
sky: 'bg-sky-100 text-sky-800',
} as const satisfies Record<'amber' | 'sky', string>
Then use <span className={toneClasses[tone]}>. The satisfies Record<...> check makes TypeScript report an error when a new tone is added to the union without a matching entry.
Exercise
A chart bar's height comes from an API as a number between 0 and 100. Which technique fits, and why can't you use a class like h-[${value}%]?
Show answer
Use a CSS variable set through style and a static class that reads it, for example style={{ '--h': ${value}% } as CSSProperties} with className="h-(--h)". The value cannot be listed ahead of time, and h-[${value}%] is an incomplete fragment in the source, so Tailwind would not generate the rule.