Quite often you'll need to show and hide elements in React. This could be anything from loading spinners to modal. Here's how it's done:

Let's use React's fancy new useState() hook to hold the state of our element - whether it's currently showing or not. We'll set it to false initially:

  const [showText, setShowText] = useState(false);

Now, let's add some logic to our render method:

    {showText && <div>This text will show!</div>}

This shorthand syntax means, "If showText is true, render the code to the right of the &&."

To show/hide an element, all we have to do now is change our showText value. We can do this to attaching the following onClick event to a button, element, or whatever we like:

    onClick={() => setShowText(!showText)}

Which basically means, "set the value of showText to the opposite of what it currently is, i.e, true would become false, and vice versa.

Check out this CodeSandbox:

This is part of the React bite-size series of posts. Check out the rest here!