Search code examples
reactjstailwind-css

Tailwind's background color is not being applied when added dynamically


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>
          )
      })
    }
      
    </>
  );
}

Solution

  • 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>
          )
        }
          
        </>
      );
    }