Search code examples
javascriptcssreactjstailwind-csstailwind-ui

Tailwind gradient not working when using template literals


I'm trying to adjust the following gradient:

bg-gradient-to-r from-rose-400 to-rose-50 from-${percentage}% to-${percentage}%

where percentage is a changing variable. When I replace the template literals and just write this:

bg-gradient-to-r from-rose-400 to-rose-50 from-10% to-10%

it works great, but then it's not adaptive.

I looked in the devtools, and the div does seem to get the class (the class is identical in both cases), but the selector doesn't seem to apply on it. (the class looks identical, but looking at the "styles" tab in devtools shows it's not catching the right selector.

could it be the way tailwind works that doesn't allow this? if so, what can I do to bypass that?


Solution

  • 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.

    To solve this problem:

    1. Use a safelist to keep certain classes to always be included in the final build.
    2. Always map props to static class names:
     const stops = {
       first: 'from-10% to-10%',
       second: 'from-20% to-20%',
     }
    
    1. If you can't use a preset value (e.g. you need to change it continuously), you can just set style:
    <div
     className="bg-gradient-to-r from-rose-400 to-rose-50"
     style={
       {
         "--tw-gradient-from-position": percentage,
         "--tw-gradient-to-position": percentage,
       } as React.CSSProperties
     }
    />