How to use useState hook to dynamically change background color in if statement in React
P粉158473780
P粉158473780 2023-08-14 20:21:13
0
1
555
<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>
P粉158473780
P粉158473780

reply all(1)
P粉701491897

You should set your state variable to a string, like this:

const [temperatureColor, setTemperatureColor] = useState("navyblue");

Then update the value like this:

setTemperatureColor(isChecked ? "navyblue" : "red");

And use that string value in your JSX like this:

<View style={{ color: temperatureColor }}></View>

Hope this helps.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template