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

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

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;

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles