0PricingLogin
Tailwind CSS Academy · Lesson

Conditional Classes in React

Use clsx or tailwind-merge to conditionally apply and safely merge Tailwind classes based on component props and state without class conflicts.

The Problem With String Concatenation

Applying Tailwind classes conditionally in React is straightforward at first, but naive string concatenation quickly becomes error-prone. Concatenating strings with template literals can accidentally include undefined or false in the className, leading to invalid class names in the DOM. More seriously, conflicting Tailwind utilities — like text-blue-500 and text-red-500 — do not cancel each other out; the order in the stylesheet determines which wins, not the order in your className string.

// Problematic — may include 'false' or 'undefined' in class list
function Button({ disabled, primary }) {
  return (
    <button
      className={'px-4 py-2 rounded ' +
        primary && 'bg-blue-500 text-white' +  // bug: && short-circuit
        disabled && 'opacity-50'               // 'false' in string
      }
    >
      Click me
    </button>
  );
}

Using clsx for Conditional Classes

clsx is a tiny utility that safely constructs className strings from conditionals, objects, and arrays. It filters out falsy values like false, null, and undefined, so your DOM always gets clean class names. You can pass strings, objects with boolean values, or arrays of either. Install it with npm install clsx and import it wherever you need conditional class logic.

import clsx from 'clsx';

function Button({ disabled, primary, className }) {
  return (
    <button
      className={clsx(
        'px-4 py-2 rounded font-medium transition-colors',
        primary && 'bg-blue-600 text-white hover:bg-blue-700',
        !primary && 'bg-gray-100 text-gray-900 hover:bg-gray-200',
        disabled && 'opacity-50 cursor-not-allowed',
        className  // allow caller to pass extra classes
      )}
      disabled={disabled}
    >
      Click me
    </button>
  );
}

All lessons in this course

  1. Setting Up Tailwind in Next.js
  2. Conditional Classes in React
  3. Component Variants With CVA
  4. Avoiding Class Conflicts With tailwind-merge
← Back to Tailwind CSS Academy