Home  >  Q&A  >  body text

How to use useState hook to dynamically change background color in if statement in React

<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粉158473780P粉158473780455 days ago543

reply all(1)I'll reply

  • P粉701491897

    P粉7014918972023-08-15 18:29:16

    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.

    reply
    0
  • Cancelreply