Using Tailwind CSS Colors in React Applications

Learn how to effectively use Tailwind CSS color utilities in React components with dynamic styling patterns.

reactcomponentsdynamic-stylingjsx
intermediate10 min readtutorial

Tailwind Colors in React Components

React and Tailwind CSS work well together. You can apply color utilities directly in JSX className attributes, use conditional logic for dynamic colors, and build reusable themed components.

Conditional Color Classes

function Alert({ type, children }) {
  const colorMap = {
    success: 'bg-emerald-50 text-emerald-800 border-emerald-200',
    error: 'bg-red-50 text-red-800 border-red-200',
    warning: 'bg-amber-50 text-amber-800 border-amber-200',
    info: 'bg-blue-50 text-blue-800 border-blue-200',
  };
  return (
    <div className={`border rounded-lg p-4 ${colorMap[type]}`}>
      {children}
    </div>
  );
}

Avoiding Dynamic Class Pitfalls

Tailwind scans your source files for complete class names at build time. Never construct class names dynamically with string concatenation like `bg-${color}-500` because Tailwind cannot detect them. Instead, map values to full class strings.

Using clsx for Clean Conditionals

import clsx from 'clsx';

function Button({ variant, disabled }) {
  return (
    <button
      className={clsx(
        'px-4 py-2 rounded-md font-medium transition-colors',
        variant === 'primary' && 'bg-blue-600 text-white hover:bg-blue-700',
        variant === 'secondary' && 'bg-slate-100 text-slate-700 hover:bg-slate-200',
        disabled && 'opacity-50 cursor-not-allowed'
      )}
    >
      Click me
    </button>
  );
}

Frequently Asked Questions

Why can't I use template literals for Tailwind colors in React?

Tailwind purges unused classes at build time by scanning for complete class strings. Template literals like `bg-${color}-500` are not detectable, so those classes get removed. Use a mapping object instead.

Should I use inline styles or Tailwind classes for dynamic colors in React?

Prefer Tailwind classes with mapping objects for a fixed set of colors. Use inline styles only when the color value is truly dynamic, such as a user-selected color from a picker.

Try Our Color Tools

50+ free tools for Tailwind CSS developers. No signup required.

Explore Tools