Home > Mobile >  Why is my decoration-${some_color} class not working correctly?
Why is my decoration-${some_color} class not working correctly?

Time:02-05

I have been trying to change the underline color decoration of some text according to a specific value given to a React component via this method:

<span className={`underline underline-offset-4 decoration-4 decoration-${decorationColor ? decorationColor : 'primary'}`}> {sentence.text}</span>

However, it is not working correctly. When I inspect the HTML file it has indeed the color I wrote, for instance: decoration-secondary. Nevertheless, the text doesn't appear to be changing accordingly.

If I write directly 'decoration-secondary' instead of passing 'secondary' within the props and then using decoration-${decorationColor ? decorationColor : 'primary'}, it suddenly works.

I found out that this only happens whenever I had not previously directly written the class name within the file. For example: I have used 'bg-primary', 'bg-secondary', and several times in other parts of the app, and thus, when using `bg-${decorationColor ? decorationColor : 'primary'}' it just works perfectly.

CodePudding user response:

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

`underline underline-offset-4 decoration-4 decoration-${decorationColor ? decorationColor : 'primary'}

…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

function  myDecoStyle(decorationColor) {
if(decorationColor) 
   return "underline underline-offset-4 decoration-4 decoration-" decorationColor;
else 
   return "underline underline-offset-4 decoration-4 decoration-primary";
}

where decorationColor is your colour value you are passing here.

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.

And use it like

<span className={`${myDecoStyle(secondary)}`}> {sentence.text}</span>

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

  • Related