How do you show or hide elements in React?

Matthew C.

The problem

You have an element that you would like to show or hide, for example an element that is shown or hidden when a user clicks a button. How do you conditionally render an element?

The solution

There are three common ways to conditionally render elements in JSX: using the logical AND (&&) operator, using the conditional (ternary) operator, and using an if statement.

Using the logical AND (&&) operator

You can use the logical AND (&&) operator to conditionally render an element based on a boolean state value:

export default function MyComponent() { const [isOpen, setIsOpen] = useState(false); function toggle() { setIsOpen((isOpen) => !isOpen); } return ( <div className="App"> {isOpen && <Popup />} <button onClick={toggle}>Toggle show</button> </div> ); }

In the example code above, the component Popup is initially not shown. When the “Toggle show” button is clicked once, isOpen is set to true. MyComponent re-renders and the component Popup is rendered as a React element. If the button is clicked again, isOpen is set to false and the Popup component is not rendered.

The issue with using the && operator is that you may end up unintentionally rendering 0 instead of nothing if the value to the left of the && operator is 0, which would be the case in the following code if the items prop was an array with no items.

function ItemList({ items }) { return ( <div> <ul> {items.length && items.map((item) => <li key={item.id}>{item.name}</li>)} </ul> </div> ); }

The && operator evaluates the values it compares, the operands, from left to right. It returns immediately with the value of the first falsy value it finds. If all values are truthy, the last evaluated value is returned. This is why 0 would be displayed if the value of items.length is 0. The length of [] is 0. You can fix this by making sure that the value is a boolean, for example:

!!items.length && ... // or items.length > 0 && ... // or Boolean(items.length) && ...

Using the conditional (ternary) operator

You can use a ternary operator to conditionally render an element without having to worry about converting values to booleans:

function ItemList({ items }) { return ( <div> <ul> {items.length ? items.map((item) => <li key={item.id}>{item.name}</li>) : null} </ul> </div> ); }

Using an if statement

You can also use an if statement instead of a ternary operator if you prefer the syntax:

function ItemList({ items }) { let itemsElements = null; if (items.length) { itemsElements = items.map((item) => <li key={item.id}>{item.name}</li>); } return ( <div> <ul>{itemsElements}</ul> </div> ); }

Get Started With Sentry

Get actionable, code-level insights to resolve React performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a React project and note your DSN

  3. Grab the Sentry React SDK

npm install @sentry/react
  1. Configure your DSN
import React from "react"; import ReactDOM from "react-dom"; import * as Sentry from "@sentry/react"; import App from "./App"; Sentry.init({ dsn: "https://<key>@sentry.io/<project>" }); ReactDOM.render(<App />, document.getElementById("root"));

Check our documentation for the latest instructions.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.