Home > Software engineering >  Dynamic gradient colour in Tailwinds comes up invisible
Dynamic gradient colour in Tailwinds comes up invisible

Time:11-08

I want dynamic gradients in Tailwinds, eg:

className={`bg-gradient-to-b from-[${gradientStart}] to-[${gradientEnd}]`}

but I notice some colours come up invisible sometimes. If I explicitly hardcode the colours, refresh the browser, and then revert the change, the colours show up. Any idea why this is happening and how to fix?

CodePudding user response:

From the docs:

Don't construct class names dynamically

<div ></div>

In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full: Always use complete class names

<div ></div>

As long as you always use complete class names in your code, Tailwind will generate all of your CSS perfectly every time.

​So you can't actually do that... you'll probably have to use a map and write them all out:

const gradStartMap = {
    value1: "from-...",
    value2: "from-...",
    value3: "from-...",
};

const gradEndMap = {
    value1: "to-...",
    value2: "to-...",
    value3: "to-...",
};

and then use that:

className={`bg-gradient-to-b ${gradStartMap[gradientStart]} ${gradEndMap[gradientEnd]}`}

which is admittedly uncool, but hey, if Tailwind didn't purge classnames, your bundle would be massive.

CodePudding user response:

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

`bg-gradient-to-b from-[${gradientStart}] to-[${gradientEnd}]`

…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  myGradient(gradientStart,gradientEnd) {
return "bg-gradient-to-b from-["  gradientStart  "] to-["  gradientEnd  "]";
}

where gradientStart,gradientEnd is your colour values 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

className={`${myGradient(red-200,green-300)}`}

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

  • Related