Skip to content

You can’t generate classes dynamically in Tailwind

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.

So instead I made a list of possible color options in a switch, and generated the class:

const getColorClass = (color) => {
  switch (color) {
    case 'green': return 'text-green-500'
    case 'blue': return 'text-blue-500'
    case 'red': return 'text-red-500'
    default: return ''
  }
}

And I used this function in my classes:

<h1 className={`mt-10 ${getColorClass(color)}`}>
...

A “quick way” is to write the classes you might need in a comment, like this:

/* possible Grid values are grid-cols-1 grid-cols-2 grid-cols-3 */
<div className={`grid grid-cols-${data[0].length}`}>
→ Download my free CSS Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about css: