10

I am trying to set dynamic background colors using Tailwind.

However, the background color is not being applied to the div. I am confused because when I check the inspector, I can see that in the browser, the correct bg-${colors[index]} was applied to each div, but the color is not being rendered.

const colors = ['#7a5195', '#bc5090','#ef5675']

export default function App() {
  const names = ['Tyler', "Charles", 'Vince']
  let labels = {}

  names.forEach((name,index)=>{
    labels[name] = `bg-[${colors[index]}]`
  })

  return (
    <>
    {
      names.map((name)=>{
        return(
          <div className={`${labels[name]}`}>
        {name}
      </div>
          )
      })
    }
      
    </>
  );
}
Tyler Morales
  • 1,440
  • 2
  • 19
  • 56
  • You can use a whitelist https://stackoverflow.com/questions/60989191/purgecss-whitelist-patterns-with-tailwindcss – bill.gates Jun 02 '22 at 20:23

3 Answers3

16

in Tailwind you can't use dynamic class naming like bg-${color}.

This because when Tailwind compiles its CSS, it looks up over all of your code and checks if a class name matches.

If you want dynamic name classes you should write all the class name.

But for your specific use case, I would not use the JIT of Tailwind and instead use the style attribute and dynamically change the backgroundColor value.

It will use less CSS and also give you less headache.

Finally, this is my suggestion

const colors = ['#7a5195', '#bc5090','#ef5675'];

export default function App() {
  const names = ['Tyler', "Charles", 'Vince']
  const labels = {};

  names.forEach((name, index) => {
    labels[name] = colors[index];
  });

  return (
    <>

    {
      names.map((name) => (
        <div style={{ backgroundColor: `${labels[name]}` }}>
          {name}
        </div>
      )
    }
      
    </>
  );
}
Vexcited
  • 368
  • 3
  • 7
2

You can also add classes to your safelist in your tailwind config.

// tailwind.config.js

// Create an array for all of the colors you want to use
const colorClasses = [
  '#7a5195', 
  '#bc5090',
  '#ef5675'
];

module.exports = {
  purge: {
    content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
    // Map over the labels and add them to the safelist
    safelist: [
      ...colorClasses.map((color) => `bg-${color}`)
    ],
  },
  darkMode: false, // or 'media' or 'class'
  variants: {
    extend: {},
  },
  plugins: [require("@tailwindcss/forms")],
}

This way you can use the colors that were included in the colorClasses array dynamically as they will not be purged.

Note: If you want to do bg-blue-500 for example, you'll need to include all of the color weights as part of the safelist (as well as add that color to the array).

...colorClasses.map((color) => `bg-${color}-500`)
Tim
  • 21
  • 2
  • You can use regular expressions to safe multiple classes at once. See https://tailwindcss.com/docs/content-configuration#safelisting-classes – rttmax Jul 31 '23 at 14:40
-3

Try this code

className={`bg-[${color}]`}