Languages
[Edit]
EN

React - how to show or hide element (class component)

0 points
Created by:
Kevin
797

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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - show or hide element (class component)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join