A simple method to show/hide elements in React using Hooks

Quite often you'll need to show and hide elements in React. This could be anything from loading spinners to modals. Let's walk through how it's done - theres a working example at the end, so make sure to check it out).

We'll 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 &&." This is where you will place the component (or JSX) that you want to show or hide.

To show/hide an element, all we have to do now is change the boolean value of our showText state object. We can do this to attaching the following onClick event to a button, element, other event 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.


If you are starting to dive into hooks, or looking to up your React game in general, make sure to check out React - The Complete Guide (incl Hooks, React Router, Redux) by Academind. He goes in depth with a number of React concepts in a fun and entertaining way. I was creating React apps in no time with his course!


Check out this CodeSandbox:

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