React - how to show or hide element
In this article, we would like to show you how to show or hide elements in React.
One button solution
In below example, we present a simple solution with one button
that hides and shows our <div>My element</div>
element.
We use React.useState
hook to store the state of our element (if it's visible or not).
By default the element is hidden. To change its visibility, we need to pass negated visible
argument to the onClick
event handling function.
Practical example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>
{visible ? 'Hide' : 'Show'}
</button>
{visible && <div>My element</div>}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Two buttons solution
In below example, we present a solution with two separate button
components to show and hide <div>My element</div>
element.
We use React.useState
hook to store the state of our element (if it's visible or not).
By default the element is hidden. To change its visibility we create two button
elements that call setVisible
function on click event with true
value (so our element can be visible now) or false
to hide it again.
Practical example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<button onClick={() => setVisible(true)}>Show</button>
<button onClick={() => setVisible(false)}>Hide</button>
{visible && <div>My element</div>}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );