Sub topic 7
Merging class names with cn
This chapter assumes you know React function components, basic TypeScript, and Tailwind CSS utility classes. You should also have run npx shadcn@latest init so that @/lib/utils exists in your project.
Why plain string joining fails
Components often build a class string from several sources: base styles, state-based styles, and a className prop from the caller. Joining them with a template string causes two problems.
- Falsy values such as
falseorundefinedend up in the output as literal text or stray spaces. - Tailwind utilities that set the same CSS property conflict. With
p-4 p-2, the winner is decided by the order of rules in the generated stylesheet, not by the order in your string. The result is often not what you intended.
The cn helper solves both problems with two small libraries.
The cn helper
The init command creates this file at lib/utils.ts:
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}The two steps run in order:
clsxaccepts strings, arrays, objects, and falsy values. It drops the falsy ones and returns one class string.twMergereads that string, finds utilities that target the same CSS property, and keeps only the last one.
Conditional classes
clsx accepts an object whose keys are class names and whose values are conditions.
import { cn } from "@/lib/utils"
type BadgeProps = { active: boolean; className?: string }
export function Badge({ active, className }: BadgeProps) {
return (
<span
className={cn(
"rounded px-2 py-1 text-sm",
{ "bg-primary text-primary-foreground": active },
!active && "bg-muted text-muted-foreground",
className
)}
>
{active ? "Active" : "Inactive"}
</span>
)
}Each argument can be a different shape. Strings are always included, the object includes its key only when the value is truthy, and !active && "..." produces false when the condition fails, which clsx discards.
Letting callers override styles
Put the caller's className last. Because twMerge keeps the last conflicting utility, the caller wins.
<Badge active className="px-4" />Here the base string has px-2 and the caller passes px-4. cn("px-2 py-1", "px-4") returns "py-1 px-4". Only px-4 remains, and py-1 is untouched because it does not conflict.
twMerge understands Tailwind's grammar. It knows that p-4 overrides px-2 when it comes later, and that text-sm (font size) does not conflict with text-primary (color).
Common errors
- Caller class placed first.
cn(className, "px-2")makes the component's defaults win, so overrides silently do nothing. PutclassNamelast. - Skipping cn for a plain template string. `
${base} ${className}` leaves conflicting utilities in place, and the result depends on stylesheet order. - Custom class names that twMerge cannot classify. It only knows built-in Tailwind groups. If you extend the theme with custom font sizes or colors, you may need to configure
extendTailwindMergeso those names are recognized as conflicting. - Dynamically assembled class names. Writing `
bg-${color}-500breaks Tailwind's scanner, which needs complete class names in your source.cn` cannot fix this. Use full literal strings instead.
What comes next
The button component in the next chapter uses cn to combine variant classes from cva with the caller's className, so this helper is what makes variants overridable.
Exercise
What does cn("px-2 py-1", false, { "font-bold": true }, "px-4") return, and why?
Show answer
It returns "py-1 font-bold px-4". clsx drops the false and includes "font-bold" because its condition is true, producing "px-2 py-1 font-bold px-4". twMerge then removes "px-2" because the later "px-4" targets the same property, and leaves "py-1" and "font-bold" alone.
Exercise
A Button spreads cn(className, buttonVariants({ variant })), and a caller passes className="bg-red-500", but the button stays the default color. What is wrong and how do you fix it?
Show answer
The caller's className is first, so the variant's bg-primary is last and wins the merge. Reorder to cn(buttonVariants({ variant }), className) so the caller's class comes last.