How to correctly reverse a boolean with the ! operator

Viewed 166

I am working with Material UI and React for the first time doing an exercise and I cannot enable a button once clicked a second time after it was disabled.

here is the code:

const [hello, setHello] = useState(true)
  <Button variant='contained' color='primary' disabled={hello ? false : true} onClick={() => setHello(!hello)}>
    Click Me
  </Button>

When the page starts the button is enabled

enter image description here

and when I click for the first time it becomes disabled as it should

enter image description here

The problem is that it stays disabled when clicked again. Shouldn't setHello(!hello) change hello into its opposite boolean value?

2 Answers

The correct way to toggle a boolean value in a React state update is to use a functional state update.

onClick={() => setHello(hello => !hello)}

The button's disabled attribute could also use a little applied Boolean Zen since the hello state is already a boolean value there's no need to use a ternary operator just to assign a boolean value.

disabled={!hello}

The bigger issue you have though is after disabling the button it's now no longer clickable, so you'll need some other means to toggle the hello state back in order to re-enable the button.

Try this.

const [hello, setHello] = useState(true)
<Button variant='contained' color='primary' disabled={!hello} onClick={() => setHello(hello => !hello)}>
    Click Me
</Button>
Related