Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Keenan Constance
To show or hide another component on click in React:
onClick
prop on an element.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> ); }
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.
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
.
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
.
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.
<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.
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>