Search code examples
reactjsuse-effectuse-state

How to change color in react on button click using state


i have set up state to change the color of my background

const [bgClr, setBgClr] = useState('white');

The button whose background colors needs to be changed is

<Button
            onClick={AnnualHandler}
            variant="outline-light"
            style={{ background: {bgClr} }}>
            <div
              className="pt-3 pb-3 ml-3 mr-3"
              style={{ background: '#f8f9fa' }}>
              <h4 style={{ color: 'var(--main)' }}>
                <b>$ 15</b>
              </h4>
            </div>
          </Button>

and the handler is

const AnnualHandler = () => {
    setBgClr('yellow');
    console.log(bgClr);
  };

But on clicking, the background color is not changing. Should useEffect be used here?


Solution

  • Can be done like this:

    // import React from "react";
    
    const App = () => {
      const [bgClr, setBgClr] = React.useState("white");
    
      const annualHandler = () => {
        setBgClr("yellow");        
      };
    
      return (
        <div>
          <button
            onClick={annualHandler}
            variant="outline-light"
            style={{ background: { bgClr } }}
          >
            <div className="pt-3 pb-3 ml-3 mr-3" style={{ background: bgClr }}>
              <h4 style={{ color: "var(--main)" }}>
                <b>$ 15</b>
              </h4>
            </div>
          </button>
        </div>
      );
    };
    
    // export default App;
    
    ReactDOM.render(<App />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="root"></div>