Home > database >  Tailwind css has unexpected behavior using React
Tailwind css has unexpected behavior using React

Time:06-18

So I have an array of colors

 let colors=["red-500","blue-500","green-500","yellow-500","cyan-500","white-500","orange-500"]

and i wanna use a specific color depending on a number

<h1 className={`bg-${colors[index]}`}></h1>

the colors are not always applied as intended for example sometimes it always be red or white has anyone encountered similar issues with tailwind css react ?

CodePudding user response:

Tailwind will only build styles for classes that it detects in your code—but it does not actually run your source code and won’t detect dynamically constructed class names. Therefore, you must include the complete class name in your strings.

The styles that are working (like red and white) are probably included elsewhere in your code, and make it into the build, while the others are not.

Don't construct class names dynamically

<div ></div>

Always use complete class names

<div ></div>

Source: Dynamic class names - Tailwind CSS

CodePudding user response:

While the answer from @quartzic is a perfectly acceptable, I'd like to present an alternative.

The missing styles is most likely caused by Tailwind purging all styles that it doesn't detect being using anywhere in your code. This purge functionality can be configured by defining a safelist - a list of classes that shouldn't be purged under any circumstances.

In your case, I'd add the background color classes you want to use, to the safelist and you wont have to change anything in your React component. This is done in the tailwind.config.js file:

module.exports = {
  // ...
  safelist: [
    'bg-red-500',
    'bg-blue-500',
    'bg-green-500',
    'bg-yellow-500',
    'bg-cyan-500',
  ]
  // ...
}

The downside is that it might increase your style bundle size, if your safelist includes classes that turned out to not be used anyways. In you cause, this doesn't seem to be an issue though.

This safelist can even use regular expressions (although, I'd be vary of using that, as it might increase bundle size unexpectedly).

You can read more in the Tailwind documentation

  • Related