Conditional Classes with clsx or classnames
What you'll learn: How to cleanly apply Tailwind utility classes based on props or state without creating messy string concatenation nightmares.
The String Concatenation Problem
When applying Tailwind classes conditionally, you might start with template literals or string concatenation. This quickly becomes unreadable:
// Messy and error-prone
<button className={`px-4 py-2 rounded ${isActive ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'} ${disabled ? 'opacity-50 cursor-not-allowed' : ''} ${size === 'large' ? 'text-lg' : 'text-sm'}`}>
Those spaces, empty strings, and nested ternaries create bugs and maintenance headaches.
Enter clsx (or classnames)
clsx is a tiny utility that intelligently joins class names together. It accepts strings, objects, arrays, and automatically filters out falsy values:
import clsx from 'clsx';
function Button({ isActive, disabled, size, children }) {
return (
<button className={clsx(
'px-4 py-2 rounded',
isActive ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700',
disabled && 'opacity-50 cursor-not-allowed',
size === 'large' ? 'text-lg' : 'text-sm'
)}>
{children}
</button>
);
}
Even cleaner with object syntax:
<button className={clsx(
'px-4 py-2 rounded',
{
'bg-blue-500 text-white': isActive,
'bg-gray-200 text-gray-700': !isActive,
'opacity-50 cursor-not-allowed': disabled,
'text-lg': size === 'large',
'text-sm': size !== 'large'
}
)}>
Why It Matters
Think of clsx as a smart filter: you toss in all your conditional classes (some true, some false), and it returns only the valid, space-separated string. No extra spaces, no undefined, no empty strings cluttering your DOM.
Key Takeaway: Use clsx or classnames to transform messy conditional Tailwind classes into readable, maintainable code by letting the library handle the filtering and joining logic for you.