1. Using Template Literals (Basic Way)
Good for simple conditions:
1<div className={`p-4 ${isActive ? "bg-blue-500" : "bg-gray-300"}`}>
2 Hello!
3</div>
1<div className={`p-4 ${isActive ? "bg-blue-500" : "bg-gray-300"}`}>
2 Hello!
3</div>
You can also chain multiple conditions:
1<div className={`text-white ${isActive ? "bg-blue-500" : ""} ${isDisabled ? "opacity-50" : ""}`}>
2 Button
3</div>
1<div className={`text-white ${isActive ? "bg-blue-500" : ""} ${isDisabled ? "opacity-50" : ""}`}>
2 Button
3</div>
2. Using clsx or classnames Libraries (Recommended)
For cleaner and more readable code, use libraries like clsx or classnames.
Installation:
1import clsx from "clsx";
2
3function Button({ isActive, isDisabled }) {
4 return (
5 <button
6 className={clsx(
7 "px-4 py-2 text-white rounded",
8 isActive ? "bg-blue-600" : "bg-gray-400",
9 isDisabled && "opacity-50 cursor-not-allowed"
10 )}
11 >
12 Submit
13 </button>
14 );
15}
16
1import clsx from "clsx";
2
3function Button({ isActive, isDisabled }) {
4 return (
5 <button
6 className={clsx(
7 "px-4 py-2 text-white rounded",
8 isActive ? "bg-blue-600" : "bg-gray-400",
9 isDisabled && "opacity-50 cursor-not-allowed"
10 )}
11 >
12 Submit
13 </button>
14 );
15}
16
This approach:
- Keeps logic clean and scalable
- Ignores falsy values like
undefined and false
- Works beautifully with Tailwind's utility-first nature
3. Combining with Tailwind Variants (like group, peer)
Sometimes, you can avoid JS conditionals entirely by using Tailwind’s utility classes and selectors like:
group-hover:
peer-invalid:
dark:
hover:, focus:, etc.
For example:
1<button className="group">
2 <span className="group-hover:text-blue-500">Hover me!</span>
3</button>
1<button className="group">
2 <span className="group-hover:text-blue-500">Hover me!</span>
3</button>