Next.js Discord

Discord Forum

Change Style with useState

Answered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
I am trying to render a div with a specified background that comes from a use state, even tho the data is being updated, the style isn't being applied.

const [backgroundColorInput, setBackgroundColorInput] = useState("#fcba03");
<div
  onClick={() => alert(hexToRgb(backgroundColorInput))}
  className="w-24 h-24"
  style={{
    backgroundColor: `rgb(${hexToRgb(backgroundColorInput)});`
  }}
/>
<input
  type="text"
  className="w-20 bg-transparent border border-white/20 text-white text-xs text-center px-2 outline-none"
  value={backgroundColorInput}
  onChange={(e) => { e.preventDefault(); setBackgroundColorInput(e.currentTarget.value) }}
/>
Answered by Polar bear
I think I figured out what was happening. seems like passing the data inside rgb() obfuscates the state (just like SQL when you're attempting to index for a function), so putting it out of the function makes it work.

<div
  onClick={() => alert(hexToRgb(backgroundColorInput))}
  className="w-24 h-24 bg-[rgb(var(--background-color))]"
  style={{
    "--background-color": `${hexToRgb(backgroundColorInput)}`
  } as React.CSSProperties}
/>
View full answer

5 Replies

does console logging backgroundColorInput shows the correct color value
try inspect element on the div and see what values comes up in the inspector?
Polar bearOP
I think I figured out what was happening. seems like passing the data inside rgb() obfuscates the state (just like SQL when you're attempting to index for a function), so putting it out of the function makes it work.

<div
  onClick={() => alert(hexToRgb(backgroundColorInput))}
  className="w-24 h-24 bg-[rgb(var(--background-color))]"
  style={{
    "--background-color": `${hexToRgb(backgroundColorInput)}`
  } as React.CSSProperties}
/>
Answer
Polar bearOP
Ah im glad it worked out