Variable number of class strings or conditional values
Combined class string with falsy values filtered out
// Basic usage
cn('text-lg', 'font-bold') // 'text-lg font-bold'
// Conditional classes
cn('base-class', isActive && 'active-class', 'another-class')
// Result: 'base-class active-class another-class' (if isActive is true)
// Result: 'base-class another-class' (if isActive is false)
// With null/undefined
cn('text-lg', null, undefined, 'font-bold') // 'text-lg font-bold'
// Practical example
function Button({ primary, disabled }) {
return (
<button className={cn(
'btn',
primary && 'btn-primary',
!primary && 'btn-secondary',
disabled && 'opacity-50'
)}>
Click me
</button>
);
}
Combine Tailwind classes with proper handling of conditionals
This utility function merges multiple class strings, filtering out falsy values (false, null, undefined) for conditional styling.