skip to Main Content

I’m a beginner with react and when I’m using useState to change name of the button, it does not work as intended.
Specifically: when I’m pushing the button it’s name "Unclicked" must change to "Clicked" and when I push it again it should change back to "Unclicked" and so on. In reality, when I click the button it changes to "Clicked" in one click but to change it back, the button must be pushed twice.

My code

the result

Well, I’m expecting the button to change it’s name on only one click.

2

Answers


  1. You are wrongly using clicked variable. it will be reset to 0 every time component re-renders.

    change to

    if(buttonName === 'Unclicked')
    ...
    
    Login or Signup to reply.
  2. You should change your code as following!

    const Test = () => {
    const [buttonName, setButtonName] = useState("Unclicked");
    
    return (
        <div>
            <h1>Test</h1>
            <Button onClick={() => {buttonName == "Unclicked" ? setButtonName("Clicked") : setButtonName("Unclicked")}} variant="contained">
                {buttonName}
            </Button>
        </div>
    )
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search