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?
CodePudding user response:
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>
CodePudding user response:
The main issue in your code is the way you set the bgClr
value to the background of the button.
<Button style={{ background: {bgClr} }}>
Don't do that. Just directly set bgClr
to the Button like this.
<Button style={{ background: bgClr }}>
Note :-
const AnnualHandler = () => {
setBgClr('yellow');
console.log(bgClr);
};
The above code snippet shows to us that you’re trying to get the updated state after the setBgClr
run. But it won’t happen because State updates in React are asynchronous. So that you will get the old value even after you change the colour to yellow
.
Resource - https://reactjs.org/docs/state-and-lifecycle.html
Full Code
import { useState } from "react";
export default function App() {
const [bgClr, setBgClr] = useState("white");
const AnnualHandler = () => {
setBgClr("yellow");
};
return (
<button onClick={AnnualHandler} style={{ background: bgClr }}>
Change
</button>
);
}
Codesandbox - https://codesandbox.io/s/change-the-color-of-the-button-69327076-wpgyj?file=/src/App.js
CodePudding user response:
You need to assign the actual value of bgClr
, while you assigning an object:
style={{ backgroundColor: bgClr }}>
CodePudding user response:
You did everything correct but only the css attribute background
style={{ background: bgClr }}
The correct way is
style={{ backgroundColor: bgClr }}>