Brad Farberman
Feb 19, 2021

--

Toggling Shouldn’t Be Mind-Boggling

It doesn’t have to be like this!

Hey, you! Yes, you there. Wanna learn how to toggle in React? Let’s do it.

Let’s make a button that says “Hello.” When you click it, it will say, “Goodbye.”

Let’s start with a class component. Maybe call it Toggle.js.

First, in your state, set hello to true.

Then let’s write a toggle function. We want to set hello here to the opposite of hello, so use a bang operator.

Then, under render and return, make a button. Pass this.toggle into the onClick, and then try a ternary:

{this.state.hello? “Hello” : “Goodbye”}

Lastly, bring your toggle component into your main container:

<Toggle></Toggle>

That’s it! It’s not that hard. Try it out!

--

--

Brad Farberman

Brad Farberman is a musician and web developer based in Brooklyn, NY.