Published on

How to Use Dynamic Classnames in Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Use Dynamic Classnames in Tailwind CSS

When working with Tailwind CSS in React or Next.js projects, dynamically generating class names can be tricky due to Tailwind's Just-in-Time (JIT) compiler. Tailwind doesn’t parse dynamic class names, so they need to be handled correctly.

1. The Problem with Dynamic Class Names

Tailwind’s JIT mode scans your project for class names at build time and removes any unused styles. If you use dynamic class names like:

<button className={`bg-${color}-500`}>Click me</button>

Tailwind will not generate styles for bg-${color}-500 because it doesn't recognize it.

2. Solutions to Dynamically Generate Tailwind Class Names

2.1 Using Conditional Strings

Instead of dynamically constructing class names, define the full class name conditionally:

<button className={color === 'primary' ? 'bg-primary-500' : 'bg-secondary-500'}>Click me</button>

2.2 Using a Configuration Object

A safer approach is to define styles in an object and reference them:

const buttonConfig = {
  primary: 'bg-primary-500 text-white',
  secondary: 'bg-secondary-500 text-black',
}

;<button className={buttonConfig[color]}>Click me</button>

2.3 Using the clsx or classnames Library

The clsx and classnames libraries help conditionally merge Tailwind classes:

npm install clsx
import clsx from 'clsx'

;<button className={clsx('px-4 py-2', color === 'primary' && 'bg-primary-500')}>Click me</button>

2.4 Using Tailwind’s Safelist Feature

You can explicitly safelist class patterns in tailwind.config.js:

module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  safelist: [
    {
      pattern: /bg-(red|blue|green|yellow)-(500|700)/,
      variants: ['hover', 'focus'],
    },
  ],
}

This ensures Tailwind generates the necessary styles even if they are dynamically applied.

3. FAQ

Why isn’t my dynamic Tailwind class applying?

Tailwind removes unused styles during build. If a class is dynamically generated, Tailwind won’t detect it.

Can I use template literals for Tailwind classes?

No, Tailwind does not recognize dynamically constructed class names. Use a predefined object or safelist them.

What is the best way to apply dynamic Tailwind classes?

Use conditionals, clsx, or safelisting to ensure your styles are generated properly.