Author avatar

Gaurav Singhal

How to Show and Hide ReactJS Components

Gaurav Singhal

  • Jan 13, 2020
  • 12 Min read
  • 2,060 Views
  • Jan 13, 2020
  • 12 Min read
  • 2,060 Views
Web Development
React

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 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 the 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

Demo2.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

Demo3.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
jsx

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.:

1
2
3
4
5
6
7
8
9
constructor() {
    super();
    this.state = {
      name: "React",
      showHideDemo1: false,
      showHideDemo2: false,
      showHideDemo3: false
    };
  }
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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"));
jsx

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 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
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;
    }
jsx

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 anotherapproach.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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;
jsx

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.

1
2
3
4
5
6
7
8
{showHideFName && (
            <tr>
              <td>First Name :</td>
              <td>
                <input type="text" id="fName" />
              </td>
            </tr>
          )}
jsx

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.

1
2
3
4
5
6
7
8
9
10
switch (name) {
      case "showHideFName":
        this.setState({ showHideFName: !this.state.showHideFName });
        break;
      case "showHideLName":
        this.setState({ showHideLName: !this.state.showHideLName });
        break;
      default:
        null;
    }
jsx

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.

1
2
3
<Demo1 
    showHideDemo1={this.state.showHideDemo1} 
/>
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
jsx

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. Stay tuned for more exciting guides.

0