3 min read
•Question 31 of 38mediumHow to use clsx/cn utility with Tailwind?
Conditional class management patterns.
What You'll Learn
- clsx for conditional classes
- cn utility pattern
- Common usage patterns
clsx Library
$ terminalBash
npm install clsxcode.txtJSX
import clsx from 'clsx'
clsx('foo', true && 'bar', 'baz')
// → 'foo bar baz'
clsx({ foo: true, bar: false, baz: true })
// → 'foo baz'
clsx(['foo', 'bar'])
// → 'foo bar'The cn Utility
code.tsTypeScript
// lib/utils.ts
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}Usage Examples
code.txtJSX
import { cn } from '@/lib/utils'
// Conditional classes
<div className={cn(
'base-class',
isActive && 'active-class',
variant === 'primary' && 'bg-blue-500',
className // allows override
)}>
// With objects
<button className={cn(
'px-4 py-2 rounded',
{
'bg-blue-500': variant === 'primary',
'bg-gray-500': variant === 'secondary',
'opacity-50 cursor-not-allowed': disabled,
}
)}>