YouTube Icon

Code Playground.

How to Show and Hide ReactJS Components

CFG

How to Show and Hide ReactJS Components

Introduction

Respond is a completely part based design used to make a rich UI and parts.

Everything in the React application is a part, so we need to mess with parts more often than not; subsequently, we might need to stow away or show various parts in light of the particular condition.

To show or conceal any part utilizing any condition, we ought to have the qualities, and in light of those qualities, we can stow away or show a part utilizing different contingent administrators.

In this aide, we will get familiar with the least difficult ways of stowing away or show parts in React.

Stow away or Show Component in React
A part is a solitary unit, and consolidating different units makes a total application. Be that as it may, imagine a scenario where we need to habitually stow away or show a part.

Suppose we have a part called Demo1, and we need to conceal it in light of the Boolean worth valid/bogus. We can utilize different restrictive administrators to accomplish this usefulness.

Make three unique documents called Demo1.js, Demo2.js, and Demo3.js, and glue the accompanying 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;

This multitude of documents are youngster parts, or free parts we will use into a parent part called index.js.

Open the document index.js and make three distinct factors into the state, similar to this.:

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

In state objects, we have three unique Boolean factors with bogus as the default esteem, and these factors will be utilized to show or conceal the particular part.

We will utilize consistent and administrator, (&&), to show parts in view of the condition alongside the button click occasion, which is made sense of in the accompanying model.

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"));

We should figure out the way this functions.

  • We have three different state factors alongside the default esteem.
  • We imported three kid parts and utilized the condition that the youngster part will be delivered provided that we get valid as a worth from the variable. In the event that the condition is valid, it will be delivered; if not, it will not.
  • We have three distinct buttons, and on snap of each button, the occasion is connected utilizing a change case to change the worth of the state factors.
  • The snap occasion is called hideComponent(), which is utilized to impact the state values in view of the button click occasion alongside the button name, which concludes that the particular state worth will be refreshed.
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 occasion, we will get a string that distinguishes which button is clicked. In view of the given string, the proper state worth will be refreshed.

This is the manner by which, in light of the state esteem and the legitimate and administrator, we can show or conceal the parts straightforwardly. Alternate ways are likewise conceivable. For instance, we can utilize sensible not, (!), and coherent or administrator, (||).

This is an illustration of how to stow away or show a part founded on the condition, however it is likewise conceivable to stow away or show components. We should perceive how that functions in the following part of this aide.

Stow away or Show Elements in React
We have seen an illustration of how to stow away or show a part, however we might have to stow away or show a particular component. We can do this utilizing another methodology.

We should bounce straightforwardly to the model, where we will make a basic structure alongside two information boxes and one submit button.

Make another record called Demo4.js and glue the accompanying 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 appears to be a gigantic record, so we should examine each and everything about this part.

Above all else, we have two different state factors alongside the default esteem.

The render () strategy contains the different structure controls alongside the submit button, however it is encircled by the condition, which seems to be this.

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

The particular table column may be delivered on the off chance that the condition will be valid; if not, it will not be apparent into the DOM. Exactly the same thing applies to the next structure controls, including the last name input box and the submit button control.

Finally, we have two extra fastens with the occasion appended, which are utilized to set off an activity by giving the exceptional string that recognizes which button was clicked.

When the button is clicked, the technique hideComponent() comes into the image. It is utilized to refresh the state values in view of the one of a kind 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 conceal the principal name input control assuming the main button is clicked; if not, the other case will be coordinated, and in the event that any of the string coordinates with the ideal worth, the fitting state worth will be refreshed.

So in light of the snap occasion, the state values will be refreshed, and in view of the Boolean worth, the particular table line stows away or shows into the DOM.

Stow away or Show Components/Elements Using Props

Props is a perused just piece of information which is utilized to consume some data or play out some activity. Consequently, props can likewise be utilized to stow away or show a part.

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

For instance, assuming that we pass props, in light of the props esteem, we can stow away or show the components, very much like in the underneath model.

Here in this model, the props we have announced is called showHideDemo1 alongside the state esteem. Presently, we should consume this props in the youngster part.

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 model, we have utilized props from the parent part and will show or stow away the div restrictively utilizing similar props.

This is one more way to deal with stow away or show various components in view of the condition or the variable's worth. The decision will be yours in light of the methodology generally reasonable for your necessities.

Conclusion
In this aide, we have learned two unique ways to deal with stow away or show either a part or a component.

Utilizing the sensible administrator is presumably the most ideal choice since it is a really hopeful method for delivering parts in view of the condition.

If it's not too much trouble, follow my other React advisers for find out more. In the event that you have any questions, go ahead and ask at Codealphabet. Remain tuned for additional thrilling aides.




CFG