Sub topic 7
Merging class names with cn
This chapter covers the cn helper that every shadcn/ui component uses to build its className. It assumes you can read React function components and TypeScript, and that you know Tailwind utility classes. You should also have run npx shadcn@latest init, which is covered in the previous chapter.
The problem cn solves
A shadcn/ui component sets default classes, and callers often want to change some of them. Plain string concatenation does not handle this well.
function Badge({ className }: { className?: string }) {
return <span className={`px-2 py-1 bg-gray-200 ${className}`}>New</span>
}
// <Badge className="bg-red-500" />
// renders: "px-2 py-1 bg-gray-200 bg-red-500"Two things go wrong here:
- When
classNameisundefined, the template literal prints the textundefinedinto the class list. - Both
bg-gray-200andbg-red-500are present. Tailwind generates its CSS in a fixed order, and the order of class names in theclassattribute has no effect. Whichever rule appears later in the generated stylesheet wins, so the caller's override may silently fail.
The cn helper fixes both problems by combining two small libraries.
The helper
The init command creates this file at lib/utils.ts, or at the alias you set in components.json.
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}The function runs in two steps. clsx turns any mix of inputs into one string. twMerge then removes Tailwind classes that conflict, keeping the last one.
Step one: clsx builds the string
clsx accepts strings, arrays, objects, and falsy values. It drops anything falsy and joins the rest with spaces.
| Input | Result |
|---|---|
| `clsx("a", "b")` | `"a b"` |
| `clsx("a", undefined, null, false)` | `"a"` |
| `clsx("a", isActive && "b")` | `"a b"` when `isActive` is true, otherwise `"a"` |
| `clsx({ "font-bold": isBold, "italic": false })` | `"font-bold"` when `isBold` is true |
| `clsx(["a", ["b", "c"]])` | `"a b c"` |
The ClassValue type that cn accepts is exported by clsx. It covers all of these shapes, so you can pass any of them to cn without a type error.
Step two: tailwind-merge resolves conflicts
twMerge knows which Tailwind utilities target the same CSS property. When two classes in the same group appear, it keeps the later one and removes the earlier one.
import { twMerge } from "tailwind-merge"
twMerge("px-2 py-1 bg-gray-200", "bg-red-500")
// "px-2 py-1 bg-red-500"
twMerge("p-4", "px-2")
// "p-4 px-2" (px-2 is a refinement of p-4, so both are kept)
twMerge("px-2", "p-4")
// "p-4" (p-4 sets all sides, so it replaces the earlier px-2)The second and third examples show a detail worth remembering. twMerge understands that p-4 covers px-2, but not the other way round. It removes a class only when a later class fully overrides it.
It also understands variants such as hover: and breakpoints. Classes with different variants do not conflict.
twMerge("hover:bg-red-500", "bg-blue-500")
// "hover:bg-red-500 bg-blue-500" (different variants, both kept)
twMerge("md:px-4", "md:px-8")
// "md:px-8"The following diagram shows the data flow through cn.
Using cn in a component
The usual pattern puts the component's defaults first and the caller's className last. Because the last conflicting class wins, the caller's classes override the defaults.
import * as React from "react"
import { cn } from "@/lib/utils"
type BadgeProps = React.HTMLAttributes<HTMLSpanElement> & {
highlighted?: boolean
}
export function Badge({ className, highlighted, ...props }: BadgeProps) {
return (
<span
className={cn(
"inline-flex items-center rounded-md px-2 py-1 text-xs bg-gray-200",
highlighted && "ring-2 ring-offset-1",
className
)}
{...props}
/>
)
}Calling <Badge className="bg-red-500 px-4" highlighted /> renders these classes:
inline-flex items-center rounded-md py-1 text-xs ring-2 ring-offset-1 bg-red-500 px-4bg-gray-200 and px-2 are gone. undefined never appears, and the conditional highlighted classes are included or skipped correctly.
The Button in the shadcn/ui source uses the same idea with cva, which the next chapter covers:
className={cn(buttonVariants({ variant, size }), className)}The variant classes come first and the caller's className comes last. This ordering is the contract that makes shadcn/ui components overridable.
Edge cases and common errors
Putting className first
If you write cn(className, "px-2"), the component's defaults override the caller. The caller's className then appears to do nothing. Always put the caller's value last.
Custom classes that tailwind-merge does not know
twMerge only understands the default Tailwind theme. If you define a custom utility, it cannot tell which group the class belongs to and treats it as unrelated to everything else.
For example, suppose you added a custom font size in your Tailwind config. twMerge("text-sm", "text-huge") might treat text-huge as a text color and remove nothing, or remove the wrong class. You can teach it about your theme with extendTailwindMerge:
import { clsx, type ClassValue } from "clsx"
import { extendTailwindMerge } from "tailwind-merge"
const twMerge = extendTailwindMerge({
extend: {
classGroups: {
"font-size": [{ text: ["huge"] }],
},
},
})
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Only do this if you actually use custom values. The default cn is correct for a standard theme. Note that the configuration format changed between tailwind-merge major versions, and Tailwind CSS v4 needs a matching tailwind-merge version, so check the documentation for the version you installed.
Conflicts are decided per class, not per intent
twMerge compares class names only. It does not know that bg-primary is a CSS variable color and bg-red-500 is a palette color. Both are in the background color group, so the later one wins. That is usually what you want.
It cannot detect conflicts between a utility and an arbitrary style. If a component sets w-full and you pass style={{ width: 200 }}, the inline style wins by CSS specificity and cn plays no part.
Dynamic class names built from fragments
cn does not change how Tailwind finds classes. Tailwind scans your source for complete class names as plain text. This code does not work:
const color = "red"
// Tailwind never sees "bg-red-500" as a whole string
<div className={cn(`bg-${color}-500`)} />Write the full class names, or look them up in a map:
const colors = {
red: "bg-red-500",
blue: "bg-blue-500",
} as const
function Dot({ color }: { color: keyof typeof colors }) {
return <span className={cn("size-3 rounded-full", colors[color])} />
}Performance
twMerge does real work on each call. It caches results internally, and for most components the cost is negligible. If a profiler shows cn as a hot spot in a very large list, move the merge outside the render path or reduce the number of distinct class combinations. Do not optimize before you measure.
Testing cn
Because cn is a pure function, it is simple to test. A small test documents the override rule for your team. This example uses Vitest.
import { describe, expect, it } from "vitest"
import { cn } from "@/lib/utils"
describe("cn", () => {
it("drops falsy values", () => {
expect(cn("a", false, undefined, null, "b")).toBe("a b")
})
it("lets the last conflicting class win", () => {
expect(cn("px-2 bg-gray-200", "bg-red-500")).toBe("px-2 bg-red-500")
})
it("keeps classes with different variants", () => {
expect(cn("hover:bg-red-500", "bg-blue-500")).toBe(
"hover:bg-red-500 bg-blue-500"
)
})
})Summary of rules
- Pass defaults first and the caller's
classNamelast. - Use
&&and objects for conditional classes, and letclsxdiscard the falsy results. - Write complete Tailwind class names so the scanner can find them.
- Extend
twMergeonly when you use custom theme values.
Exercise
A teammate writes className={cn(className, "rounded-md bg-primary px-4")} in a copied component. A page passes className="bg-destructive", but the button stays in the primary color. Explain why, and give the fix. Then state what cn("p-4", "px-2") and cn("px-2", "p-4") return.
Show answer
The caller's bg-destructive comes first, and the component's bg-primary comes last. twMerge keeps the last class in a conflict group, so bg-primary wins and the override is lost. The fix is to put the caller's value last: cn("rounded-md bg-primary px-4", className). cn("p-4", "px-2") returns "p-4 px-2" because px-2 refines p-4 and both are kept. cn("px-2", "p-4") returns "p-4" because p-4 sets all sides and fully replaces the earlier px-2.
Exercise
Why does cn(bg-${color}-500) fail to produce the expected style in production, even though the string looks correct at runtime? Write a replacement that works for the colors "red" and "blue".
Show answer
Tailwind generates CSS by scanning source files for complete class names as text. The fragments bg-, red, and -500 are never joined in the source, so the scanner does not find bg-red-500 and does not generate the CSS rule. The fix is a lookup map with full class names, for example const colors = { red: "bg-red-500", blue: "bg-blue-500" }, then cn(colors[color]).