Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Show and Hide ReactJS Components

Nov 2, 2020 • 12 Minute Read

Introduction

React is a wholly component-based architecture used to create a rich user interface and components.

Everything in the React app is a component, so we have to play around with components most of the time; hence, we may have to hide or show different components based on the specific condition.

To show or hide any component using any condition, we should have the values, and based on those values, we can hide or show a component using different conditional operators.

In this guide, we are going to learn the simplest ways to hide or show components in React.

Hide or Show Component in React

A component is a single unit, and combining multiple units creates a complete application. But what if we want to hide or show a component frequently?

Let’s say we have a component called Demo1, and we want to hide it based on the Boolean value true/false. We can use different conditional operators to achieve this functionality.

Create three different files called Demo1.js, Demo2.js, and Demo3.js, and paste the following lines of source code into them:

Demo1.js

      import React, { Component } from "react";

class Demo1 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    return <div>This is Demo1 component</div>;
  }
}

export default Demo1;
    

Demo2.js

      import React, { Component } from "react";

class Demo2 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    return <div>This is Demo2 component</div>;
  }
}

export default Demo2;
    

Demo3.js

      import React, { Component } from "react";

class Demo3 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    return <div>This is Demo3 component</div>;
  }
}

export default Demo3;
    

All these files are child components, or independent components we are going to use into a parent component called index.js.

Open the file index.js and create three different variables into the state, like this.:

      constructor() {
    super();
    this.state = {
      name: "React",
      showHideDemo1: false,
      showHideDemo2: false,
      showHideDemo3: false
    };
  }
    

In state objects, we have three different Boolean variables with false as the default value, and these variables will be used to show or hide the specific component.

We will use logical and operator, (&&), in order to show components based on the condition along with the button click event, which is explained in the following example.

Index.js

      import React, { Component } from "react";
import { render } from "react-dom";
import Demo1 from "./Demo1";
import Demo2 from "./Demo2";
import Demo3 from "./Demo3";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      showHideDemo1: false,
      showHideDemo2: false,
      showHideDemo3: false
    };
    this.hideComponent = this.hideComponent.bind(this);
  }

  hideComponent(name) {
    console.log(name);
    switch (name) {
      case "showHideDemo1":
        this.setState({ showHideDemo1: !this.state.showHideDemo1 });
        break;
      case "showHideDemo2":
        this.setState({ showHideDemo2: !this.state.showHideDemo2 });
        break;
      case "showHideDemo3":
        this.setState({ showHideDemo3: !this.state.showHideDemo3 });
        break;
      default:
        null;
    }
  }

  render() {
    const { showHideDemo1, showHideDemo2, showHideDemo3 } = this.state;
    return (
      <div>
        {showHideDemo1 && <Demo1 />}
        <hr />
        {showHideDemo2 && <Demo2 />}
        <hr />
        {showHideDemo3 && <Demo3 />}
        <hr />
        <div>
          <button onClick={() => this.hideComponent("showHideDemo1")}>
            Click to hide Demo1 component
          </button>
          <button onClick={() => this.hideComponent("showHideDemo2")}>
            Click to hide Demo2 component
          </button>
          <button onClick={() => this.hideComponent("showHideDemo3")}>
            Click to hide Demo3 component
          </button>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

Let’s understand how this example works.

  • We have three different state variables along with the default value.
  • We imported three child components and used the condition that the child component will be rendered only if we get true as a value from the variable. If the condition is true, then it will be rendered; otherwise, it will not.
  • We have three different buttons, and on click of every button, the event is attached using a switch case in order to change the value of the state variables.
  • The click event is called hideComponent(), which is used to change the state values based on the button click event along with the button name, which decides that the specific state value will be updated.
      switch (name) {
      case "showHideDemo1":
        this.setState({ showHideDemo1: !this.state.showHideDemo1 });
        break;
      case "showHideDemo2":
        this.setState({ showHideDemo2: !this.state.showHideDemo2 });
        break;
      case "showHideDemo3":
        this.setState({ showHideDemo3: !this.state.showHideDemo3 });
        break;
      default:
        null;
    }
    

From the button click event, we will get a string that identifies which button is clicked. Based on the given string, the appropriate state value will be updated.

This is how, based on the state value and the logical and operator, we can show or hide the components directly. Other ways are also possible. For example, we can make use of logical not, (!), and logical or operator, (||).

This is an example of how to hide or show a component based on the condition, but it is also possible to hide or show elements. Let’s see how that works in the next section of this guide.

Hide or Show Elements in React

We have seen an example of how to hide or show a component, but we may need to hide or show a specific element. We can do this using another approach.

Let’s jump directly to the example, where we will create a simple form along with two input boxes and one submit button.

Create a new file called Demo4.js and paste the following lines of source code.

      import React, { Component } from "react";

class Demo4 extends Component {
  constructor() {
    super();
    this.state = {
      showHideFName: true,
      showHideLName: true
    };
    this.hideComponent = this.hideComponent.bind(this);
  }

  hideComponent(name) {
    switch (name) {
      case "showHideFName":
        this.setState({ showHideFName: !this.state.showHideFName });
        break;
      case "showHideLName":
        this.setState({ showHideLName: !this.state.showHideLName });
        break;
      default:
        null;
    }
  }

  render() {
    const { showHideFName, showHideLName } = this.state;
    return (
      <div>
        <table>
          {showHideFName && (
            <tr>
              <td>First Name :</td>
              <td>
                <input type="text" id="fName" />
              </td>
            </tr>
          )}
          {showHideLName && (
            <tr>
              <td>Last Name :</td>
              <td>
                <input type="text" id="lName" />
              </td>
            </tr>
          )}
          {showHideFName && showHideLName && (
            <tr>
              <td>
                <button>Submit</button>
              </td>
            </tr>
          )}
          <tr>
            <td>
              <button onClick={() => this.hideComponent("showHideFName")}>
                Hide First Name
              </button>
            </td>
            <td>
              <button onClick={() => this.hideComponent("showHideLName")}>
                Hide Last Name
              </button>
            </td>
          </tr>
        </table>
      </div>
    );
  }
}

export default Demo4;
    

It seems like a huge file, so let’s discuss each and everything about this component.

First of all, we have two different state variables along with the default value.

The render () method contains the different form controls along with the submit button, but it is surrounded by the condition, which looks like this.

      {showHideFName && (
            <tr>
              <td>First Name :</td>
              <td>
                <input type="text" id="fName" />
              </td>
            </tr>
          )}
    

The specific table row will only be rendered if the condition will be true; otherwise, it won’t be visible into the DOM. The same thing applies to the other form controls, including the last name input box and the submit button control.

At last, we have an additional two buttons with the event attached, which are used to trigger an action by providing the unique string that identifies which button was clicked.

As soon as the button is clicked, the method hideComponent() comes into the picture. It is used to update the state values based on the unique identifier that we are getting from the button control.

      switch (name) {
      case "showHideFName":
        this.setState({ showHideFName: !this.state.showHideFName });
        break;
      case "showHideLName":
        this.setState({ showHideLName: !this.state.showHideLName });
        break;
      default:
        null;
    }
    

We have two use cases. We can hide the first name input control if the first button is clicked; otherwise, the other case will be matched, and if any of the string matches with the desired value, then the appropriate state value will be updated.

So based on the click event, the state values will be updated, and based on the Boolean value, the specific table row hides or shows into the DOM.

Hide or Show Components/Elements Using Props

Props is a read-only piece of data which is used to consume some information or perform some action. Hence, props can also be used to hide or show a component.

For example, if we pass props, based on the props value, we can hide or show the elements, just like in the below example.

      <Demo1 
    showHideDemo1={this.state.showHideDemo1} 
/>
    

Here in this example, the props we have declared is called showHideDemo1 along with the state value. Now, let’s consume this props in the child component.

      import React, { Component } from "react";

class Demo1 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    const { showHideDemo1 } = this.props;
    return <>{showHideDemo1 && <div>This is Demo1 component</div>}</>;
  }
}

export default Demo1;
    

In this example, we have used props from the parent component and will show or hide the div conditionally using the same props.

This is another approach to hide or show different elements based on the condition or the variable’s value. The choice will be yours based on the approach most suitable for your requirements.

Conclusion

In this guide, we have learned two different approaches to hide or show either a component or an element.

Using the logical operator is probably the best option because it is a pretty optimistic way to render components based on the condition.

Please follow my other React guides to learn more. If you have any queries, feel free to ask at Codealphabet. Stay tuned for more exciting guides.

Learn More

Explore these React courses from Pluralsight to continue learning: