Home > Back-end >  Template literal not working correctly with Tailwind CSS
Template literal not working correctly with Tailwind CSS

Time:07-07

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?

CodePudding user response:

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 ></div>

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

<div ></div>

So , for your case, use the following code:

<div ></div>

Hope it helps!

CodePudding user response:

TailwindCSS doesn't allow you to generate classes dynamically. So when you use the following to generate the class…

`bg-${cardColourRGB}`

…TailwindCSS will not pick that up as a valid TailwindCSS class and therefore will not produce the necessary CSS.

Instead, you must include the full name of the class in your source code. You can return the full value like this

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

where cardColourRGB is your value you are passing .

By doing it this way, the entire string for every class is in your source code, so TailwindCSS will know to generate the applicable CSS.

Read more: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth

  • Related