Search code examples
cssreactjsuser-interfacetailwind-csstemplate-literals

Template literal not working correctly with Tailwind CSS


I am passing in a Hex Colour into a prop and attempting to set the background of an element with it. Here is my code:

 let cardColourRGB: string;
 if (cardColour) {
   cardColourRGB = "[" + cardColour + "]";
   console.log(cardColourRGB);
 } else {
   cardColourRGB = "white/50"
 }

In the return function:

 <div className={`bg-${cardColourRGB}`}></div>

Passing in some colours work, but others don't. For example, passing in #AAA32E as the prop does not set the colour, but setting the colour directly works:

<div className={`bg-[#AAA32E]`}></div>

Why could this be?


Solution

  • According to the official documentation of the tailwind.css it is not preferred to have such classNames

    As document says:

    • The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

    • If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

    Don't construct class names dynamically

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

    Instead, make sure any class names you’re using exist in full

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

    So , for your case, use the following code:

    <div class="{{ cardColour ? 'bg-[#AAA32E]' : 'bg-white-50' }}"></div>
    

    Hope it helps!