25

Add utilities

Components merge their own classes with the ones you pass in. That goes through a small cn() helper built on clsx and tailwind-merge.

Setup

1.Install the packages

$ npm install clsx tailwind-merge

2.Create the helper

Components import it from @/lib/utils, so keep the path.

lib/utils.ts
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

3.Use it

Later classes win, so a className prop can override a component default.

example.tsx
import { cn } from "@/lib/utils"

<div className={cn("rounded-xl border p-4", active && "bg-muted", className)} />

Already using shadcn?

shadcn init creates lib/utils.ts and installs both packages. If that file exists, there is nothing to do here.