Show or hide another component on Click in React

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

Show or hide another component on Click in React #

To show or hide another component on click in React:

  1. Set the onClick prop on an element.
  2. When the element is clicked, toggle a state variable that tracks if the component is shown.
  3. Conditionally render the component based on the state variable.
App.js
import {useState} from 'react'; export default function App() { const [isShown, setIsShown] = useState(false); const handleClick = event => { // 👇️ toggle shown state setIsShown(current => !current); // 👇️ or simply set it to true // setIsShown(true); }; return ( <div> <button onClick={handleClick}>Click</button> {/* 👇️ show elements on click */} {isShown && ( <div> <h2>Some content here</h2> </div> )} {/* 👇️ show component on click */} {isShown && <Box />} </div> ); } function Box() { return ( <div> <h2>Box</h2> </div> ); }

show component on click

We set the onClick prop on the button element, so every time it is clicked, the handleClick function is invoked.

In our handleClick function, we simply toggle the isShown state variable.

Notice that we passed an initial value of false to the useState hook because we want the component to be hidden by default.

We passed a function to setState, because the function is guaranteed to be invoked with the current (most up to date) state.

App.js
const handleClick = event => { // 👇️ toggle shown state setIsShown(current => !current); // 👇️ or simply set it to true // setIsShown(true); };

When the next state is computed using the previous state, pass a function to setState.

Otherwise, we might get some weird race condition if the state boolean we have access to does not represent the most up to date value.

The example toggles the state boolean every time the button is clicked, but if you only want to show the element, set the state variable to true.

App.js
const handleClick = event => { // 👇️ only show element on click setIsShown(true); };

We used the logical AND (&&) operator to conditionally render the component based on the state variable.

App.js
<div> <button onClick={handleClick}>Click</button> {/* 👇️ show elements on click */} {isShown && ( <div> <h2>Some content here</h2> </div> )} {/* 👇️ show component on click */} {isShown && <Box />} </div>

The logical AND (&&) operator returns the value to the right if the value to the left is truthy.

We can use this approach because booleans, null and undefined are ignored. They simply don't render.

The following JSX expressions all render nothing.

App.js
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
Use the search field on my Home Page to filter through my more than 1,000 articles.