On click of button the background color of div does not change

On click of button the background color of div does not change
javascript
Ethan Jackson

I have a simple program where, on the click of button, I expect the background of my component color to change, but it does not. Where am I making mistake?

import { useState } from "react"; import './sixth.css'; const Sixth = () => { const [bgColor, setBgColor] = useState("white"); const bgFunc = (val)=> { setBgColor(val); } return ( <div className="sixth" style={{'background': {bgColor}}}> <button onClick={()=> bgFunc("red")}>red</button> <button onClick={()=> bgFunc("green")}>green</button> <button onClick={()=> bgFunc("blue")}>blue</button> </div> ) } export default Sixth;

Answer

The problem is in how you're applying the styling. You should not be wrapping the value of the style property in curly braces.

import { useState } from "react"; import './sixth.css'; const Sixth = () => { const [bgColor, setBgColor] = useState("white"); const bgFunc = (val)=> { setBgColor(val); } return ( <div className="sixth" style={{background: bgColor}}> <button onClick={()=> bgFunc("red")}>red</button> <button onClick={()=> bgFunc("green")}>green</button> <button onClick={()=> bgFunc("blue")}>blue</button> </div> ) } export default Sixth;

Related Articles