Search code examples
cssreactjstailwind-csstailwind-in-js

Tailwind css has unexpected behavior using React


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 ?


Solution

  • 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 class="text-{{ error ? 'red' : 'green' }}-600"></div>
    

    Always use complete class names

    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
    

    Source: Dynamic class names - Tailwind CSS