Tailwind CSS Course
Tailwind CSS
/
Intermediate

Tailwind with React

Definition

The specific patterns, pitfalls, and best practices of using Tailwind CSS within a React or JSX environment.

Explain Like I'm New

React uses `className` instead of `class`. But more importantly, React allows you to use template literals to dynamically change classes based on State, which is where developers make the biggest mistakes with Tailwind.

Real World Example

Conditionally hiding a Modal based on an `isOpen` React state.

Common Use Cases

  • React integration

Interactive Example

// ❌ THE NUMBER ONE REACT + TAILWIND MISTAKE
// String concatenation hides the class name from Tailwind's Purge engine.
function StatusBadge({ status }) {
  // If status is 'success', it generates 'bg-green-500', but Tailwind deleted that class!
  return <span className={`bg-${status === 'success' ? 'green' : 'red'}-500`}>Badge</span>
}

// ✅ THE CORRECT WAY
// Write the FULL class name so Tailwind's scanner can read it.
function StatusBadge({ status }) {
  return (
    <span className={status === 'success' ? 'bg-green-500' : 'bg-red-500'}>
      Badge
    </span>
  )
}

Interview Questions

basic

  • In React, do you write `class="bg-red-500"` or `className="bg-red-500"`?

intermediate

  • Why is it a catastrophic bug to write `className={`bg-${color}-500`}` in React?

Flash Cards

Question

class or className?

Click to reveal answer
Answer

`className`.

Question

Catastrophic bug?

Click to reveal answer
Answer

Because Tailwind's compiler runs at BUILD time, before React runs. It scans your files for full class names. It will see `bg-${color}-500`, not know what it means, and permanently delete all blue, red, and green backgrounds from your production CSS file.