How do you conditionally apply Tailwind classes in React?

clock icon

Asked 1 year ago

message icon

1

eye icon

5

I’m building a React app using Tailwind CSS, and I want to apply different classes based on some condition — like whether a button is active, a modal is open, or a form input has an error.

Right now, I’m trying something like this:

1<div className={isActive ? "bg-blue-500" : "bg-gray-300"}>
2 Click me
3</div>
1<div className={isActive ? "bg-blue-500" : "bg-gray-300"}>
2 Click me
3</div>

It works for simple cases, but as the conditionals grow more complex (e.g., multiple conditions, toggling classes), the className attribute becomes hard to manage and messy.

Is there a better, more maintainable way to handle conditional class names when using Tailwind CSS with React?

1 Answer

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:

1npm install clsx
1npm install clsx
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>

1

Write your answer here

Top Questions