Home > Software design >  Tailwind colors doesnt display when changed
Tailwind colors doesnt display when changed

Time:05-25

i got an array with colors already defined in the tailwind default color palette , as follows

colors: ["red-600", "blue-600", "pink-600", "black", "white", "yellow-600"]

I mapped over the array to produce small boxes with a background color thats defined in the array.

{colors.map((col, i) => (
        <button
          className="cursor-pointer"
          key={i}
        >
          <div
            className={`mt-3 border-2 border-solid border-black bg-${col} w-8 h-8`}
          >

enter image description here

my issue is if i change any of the colors in the array ( like changing red-600 to red-900) it doesnt display despite that both colors are defined in the default color palette

enter image description here

what could possibility be wrong here?

CodePudding user response:

I at one point had this issue while attempting something very similar to what you're currently trying... I realized that you can't set a Tailwind value partially as a variable, rather it must be the entire value if you're going to use a variable for it.

Example:

make an array strictly for bg-colors

bgColors: [
  "bg-red-600",
  "bg-blue-600", 
  "bg-pink-600", 
  "bg-black", 
  "bg-white", 
  "bg-yellow-600"
]

and now you should be able to use them as variables with the whole value instead of a partial value.

className={`${col}`} // ${col} === bg-color-###

CodePudding user response:

First, you should set colors array as a state, that thing make this component will re-render when this array change.

Second, if only order inside colors array change, it don't force this component re-render to read your state change, so you should add another state to force component re-render like [forceChangeColor, setForceChangeColor] = useState(0):

const [colors, setColors] = useState(["red-600", "blue-600", "pink-600", "black", "white", "yellow-600"])
const [forceChangeColor, setForceChangeColor] = useState(0)

const handleChangeColor = () => {
  setColors([/*set your change colors*/]) // <=== set Colors change in here
  setForceChangeColor(prev => prev   1) //<=== Make another state change to force this component re-render to re-read colors state
}


{colors.map((col, i) => (
        <button
          className="cursor-pointer"
          key={i}
        >
          <div
            className={`mt-3 border-2 border-solid border-black bg-${col} w-8 h-8`}
          >
        
  • Related