How to use useState hook to dynamically change background color in if statement in React
P粉158473780
2023-08-14 20:21:13
<p><br /></p>
<pre class="brush:php;toolbar:false;">const [temperatureColor, setTemperatureColor] = useState({color:"navyblue"});
const TemperaturIncrement = () => {
if (temperatureValue === 30) return;
const newTemperature = temperatureValue 1;
setTemperatureValue(newTemperature)
if(newTemperature >= 15 ){
setTemperatureColor({ color: isChecked ? "navyblue" : "red" });
}
}
const TemperaturDecrement = () => {
setTemperatureValue(temperatureValue - 1)
}</pre>
<p>I want to use useState in the if statement to change the background color</p>
You should set your state variable to a string, like this:
Then update the value like this:
And use that string value in your JSX like this:
Hope this helps.