You can’t generate classes dynamically in Tailwind

By

Why Tailwind cannot detect dynamically constructed class names, how to map values to complete classes, and how to safelist utilities in Tailwind CSS v4.

~~~

I wanted to have a dynamic color in Tailwind, using a syntax like this in JSX:

bg-${color}-500

But it wasn’t applied to the page because Tailwind couldn’t find for example the text bg-red-500 in the code, so the code was not added to the final CSS.

Tailwind scans source files as plain text. It can generate bg-red-500 when that complete token exists in the source, but it cannot evaluate a template literal and infer every possible result.

Map each allowed value to a complete class name:

const colorClasses = {
  green: 'bg-green-500 text-white',
  blue: 'bg-blue-500 text-white',
  red: 'bg-red-500 text-white'
}

Then use the mapped class:

<h1 className={`mt-10 ${colorClasses[color] ?? ''}`}>
  Hello
</h1>

If a class cannot appear in your templates, Tailwind CSS v4 can explicitly include it with @source inline() in your CSS:

@import "tailwindcss";
@source inline("grid-cols-{1..3}");

Prefer the map when the value controls a component variant. It is easy to review, keeps invalid values out, and lets each variant use a different combination of utilities.

Tagged: CSS · All topics
~~~

Related posts about css: