React - how to show or hide element (class component)
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 the component's state to store the state
which tells us if the element is visible or not.
By default the element is hidden. To change its visibility, we need to update the state with negated this.state.visible
value using setState()
method inside the onClick
event handling function.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
};
}
render() {
return (
<div>
<button onClick={() => this.setState({ visible: !this.state.visible })}>
{this.state.visible ? 'Hide' : 'Show'}
</button>
{this.state.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 that show and hide <div>My element</div>
element.
We use the component's state 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 setState()
method changing visible
value.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
};
}
render() {
return (
<div>
<button onClick={() => this.setState({ visible: true })}>Show</button>
<button onClick={() => this.setState({ visible: false })}>Hide</button>
{this.state.visible && <div>My element</div>}
</div>
);
}
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.