Home > OS >  Tailwind CSS unresponsive to react state change
Tailwind CSS unresponsive to react state change

Time:06-09

This very simple toggle in react is not working with tailwind CSS. When I click the "toggle color" button, the className of the div changes between bg-[#222222] and bg-[#DDDDDD], but the div never actually colors -- it has the className, but tailwind doesn't seem to be able to fill in the background property.

import React, { useState } from "react";

function App() {
  const [color, setColor] = useState('222222')
  const toggleColor = () => color === '222222' ? setColor('DDDDDD') : setColor('222222');
  return (
    <div className='h-screen w-full flex flex-col justify-center items-center'>
        <button onClick={toggleColor}>Toggle Color</button>
        <div className={`bg-[#${color}] w-[100px] h-[100px]`}></div>
    </div>
  )
}

export default App;

To clarify, if I store the full string 'bg-[#2222222]' or 'bg-[#DDDDDD]' and then drop that directly into the className, it works. (AKA, in the below code segment, the div renders with the proper color and toggles properly:

import React, { useState } from "react";

function App() {
  const [color, setColor] = useState('bg-[#222222]')
  const toggleColor = () => color === 'bg-[#222222]' ? setColor('bg-[#DDDDDD]') : setColor('bg-[#222222]');
  return (
    <div className='h-screen w-full flex flex-col justify-center items-center'>
        <button onClick={toggleColor}>Toggle Color</button>
        <div className={`${color} w-[100px] h-[100px]`}></div>
    </div>
  )
}

export default App;

However, in the larger context of the application I'm hoping to build, this doesn't do me much good. It would be much more helpful to simply store the color. It's unclear to me why the first way is not working, considering that in both cases, the full string is successfully dropped into the className. Any ideas?

CodePudding user response:

This is the expected behaviour of Tailwind and the reason is explained here: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth

One option would be to use a safe list which is described here: https://tailwindcss.com/docs/content-configuration#safelisting-classes

CodePudding user response:

Another solution for an exception like this is to ignore Tailwind and add a dynamic style to the element. For example:

<div className={'w-[100px] h-[100px]'} style={{'background-color': `#${color}`}}></div>

This might be more flexible than safelisting Tailwind classes, if you have a lot of colors or if you don't know the color value until runtime.

  • Related