0

When the App starts, the button's text is initially 'c'. When the button is clicked, it goes to toggleDisplay() and checks if unit === 'c'. If it's true, then update the unit variable to 'f'. This part works as I tested it using console.log. But the unit variable that in inside <button> tag is not updating. It's only showing 'c' but it has to toggle between 'c' and 'f'

function App() {
...
...
let unit = "c";
const toggleDisplay = () =>{
if(unit === 'c'){
    unit = "f";
    console.log(unit)
}
else{
    unit = "c";
    console.log(unit)
 }
}


return(
    <button className="temp" onClick={toggleDisplay}>
        {unit}
    </button>
)

Ps. This is actually a weather app and the toggle between 'c' and 'f' is the toggle between values of celsius and fahrenheit.

1
  • Modifying the variable will not trigger a re-render and hence update the button text. Why don't you store unit in state? Commented May 30, 2020 at 20:12

2 Answers 2

4

Use a state hook to store the unit. In your code, unit is being set to "c" every time the component updates.

import {useState} from "react";

function App() {
    const [unit, setUnit] = useState("c");
    const toggleDisplay = () => {
        if (unit === "c") {
            setUnit("f");
            console.log(unit);
        } else {
            setUnit("c");
            console.log(unit);
        }
    };
    return (
        <button className="temp" onClick={toggleDisplay}>
            {unit}
        </button>
    );
}
Sign up to request clarification or add additional context in comments.

Comments

0

An easy way to create a toggle between two elements

import {useState} from 'react'
function App() {
  const [isToggled,setToggle] = useState(false);
  const [unit,setUnit] = useState('c');

  const toggle = () => {
    setToggle(!isToggled)
    isToggled ? setUnit('c') : setUnit('f') // use ternary operator for readability
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.