Logic of "React - Use state to Toggle an Element"

Hi everyone,

I have trouble understanding the logic in the if/else statement of this exercise’s answer. I do know how the if/else statement works, but somehow I don’t see the logic behind this specific one.

The part of the code that confuses me:

toggleVisibility() {
      if (this.state.visibility == true) {
        visibility: false
      } else {
        visibility: true

So you need to click a button, and when you do the toggleVisibility method is called to show some text. Then this code checks if the this.state.visibility is true and if it is, it sets the visibility of state to false? How I interpret this, it basically would hide the text again once you clicked it.

Anyone can help me with my confusion?

Thanks a lot


the code you have given merely toggles the status of visibility. Think of it like this, if the visibility is already true, you set it to false and if it isn’t, you set it to true. You are just switching the state.

The relation to the component itself is that this logic happens after the component updates, whether it gets presented on the screen or not.

So, if I understood you correctly:starting with a blank page, you click on the button, then the text appears (=true) and will at the same time prepare the “false” so your text disappears once the button is clicked? Seems like an odd thing to do.

The code you have added is a way to solve the challenge. A simpler solution does the following:

         visibility: !this.state.visibility

The text is first not visible, thus the state is false. When clicking the button, it becomes visible.

1 Like

So the state in itself updates to “true” after you clicked the button the first time? And that’s why the “!this.state.visibility” would work. Now, I seem to get it. Thanks for your help!