JIT tailwindcss using variable in bg-[] not rendering color

Viewed 6014

when passing my color as props like this <List text="something" color="#84AB86" /> and using in the code className={'bg-[${color}] '} it does not render properly.

when looking at chrome dev tools color are added correctly like this bg-[#84AB86]

while putting the color manually without taking it from props, it does work correctly

after more testing it seems not possible either to do it like this

const color = "#84CC79"
className={`bg-[${color}]`}

any idea why

2 Answers

First of all, is that your custom class? Because tailwind does not have such class by default, you need to manually create it.

Assuming you've already done that, to use dynamic classes with JIT tailwind you need to create stub file where you list all your dynamic classes that you will use.

For example, make safelist.txt in your src folder, then add classes there just like so:

bg-[#84AB86]
bg-[#fffeee]

// etc..

And dont' forget to include this safelist.txt file to your config so tailwind could watch it.

Explanation from tailwind docs

If you are not using JIT, then you can use safelist option for PurgeCSS:

// tailwind.config.js
module.exports = {
  purge: {
    // Configure as you need
    content: ['./src/**/*.html'],
    // These options are passed through directly to PurgeCSS
    options: {
      // List your classes here, or you can even use RegExp
      safelist: ['bg-red-500', 'px-4', /^text-/],
      blocklist: [/^debug-/],
      keyframes: true,
      fontFace: true,
    },
  },
  // ...
}

From the Tailwindcss documentation

Dynamic values Note that you still need to write purgeable HTML when using arbitrary values, and your classes need to exist as complete strings for Tailwind to detect them correctly.

Don't use string concatenation to create class names --> <div className={mt-[${size === 'lg' ? '22px' : '17px' }]}></div>

Do dynamically select a complete class name --> <div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div> Tailwind doesn’t include any sort of client-side runtime, so class names need to be statically extractable at build-time, and can’t depend on any sort of arbitrary dynamic values that change on the client. Use inline styles for these situations, or combine Tailwind with a CSS-in-JS library like Emotion if it makes sense for your project.

Related