How to Show or Hide Element in React ?
Last Updated :
03 Oct, 2024
We can show or hide element in React dynamically by accessing the visibility of the elements with the help of state. We can toggle and update the state and render the variable as required.
Approach
To Show or Hide Element in React we will be using the state variable as a boolean value. We will conditionally render the component based on its value i.e. true or false. We will use a button to toggle the state from true to false and vice-versa.
We have different ways to implement the state in class and functional components
Steps to Create React Application
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure:
List of dependencies in the package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
As we discussed above we have to create few components and render them into a single parent file to execute the conditions so that we can apply the functionality of showing or hiding to some particular components. Let's create three child components and name them Child1.js, Child2.js, and Child3.js in the src folder and paste the following code into respective files.
using Class Components
In case of class components we can directly access state using this.state and modify it with the help of this.setState method.
Example: This example use the state in class components to store the boolean value to conditiona;lly render the element.
JavaScript
// Filename - App.js
import React, { Component } from "react";
import { render } from "react-dom";
import Child1 from "./Child1";
import Child2 from "./Child2";
import Child3 from "./Child3";
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
shchild1: false,
shchild2: false,
shchild3: false
};
this.hideComponent = this.hideComponent.bind(this);
}
hideComponent(varname) {
console.log(varname);
switch (varname) {
case "shchild1":
this.setState({ shchild1: !this.state.shchild1 });
break;
case "shchild2":
this.setState({ shchild2: !this.state.shchild2 });
break;
case "shchild3":
this.setState({ shchild3: !this.state.shchild3 });
break;
default:
return;
}
}
render() {
const { shchild1, shchild2, shchild3 } = this.state;
return (
<div>
{shchild1 && <Child1 />}
<hr />
{shchild2 && <Child2 />}
<hr />
{shchild3 && <Child3 />}
<hr />
<div>
<button onClick={() => this.hideComponent("shchild1")}>
Click here to hide GFG child1 component
</button>
<button onClick={() => this.hideComponent("shchild2")}>
Click here to hide GFG child2 component
</button>
<button onClick={() => this.hideComponent("shchild3")}>
Click here to hide GFG child3 component
</button>
</div>
</div>
);
}
}
export default App;
JavaScript
// Filename - Child1.js
import React, { Component } from "react";
class Child1 extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return <div>This is how GFG child component number 1 looks like.</div>;
}
}
export default Child1;
JavaScript
// Filename - Child2.js
import React, { Component } from "react";
class Child2 extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return <div>This is how GFG child component number 2 looks like.</div>;
}
}
export default Child2;
JavaScript
// Filename - Child3.js
import React, { Component } from "react";
class Child3 extends Component {
constructor() {
super();
this.state = {
name: "React"
};
}
render() {
return <div>This is how GFG child component number 3 looks like.</div>;
}
}
export default Child3;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
using Functional Components
In case of functional components we cannot access state directly. We use the useState hook to access the state in functional components.
Example: This example implements show and hide element in react with the help of useState variable to store the boolean value and toggle the value with help of buttons.
JavaScript
// Filename - App.js
import React, { useState } from "react";
import Child1 from "./Child1";
import Child2 from "./Child2";
import Child3 from "./Child3";
const App = () => {
const [shchild1, setShchild1] = useState(false);
const [shchild2, setShchild2] = useState(false);
const [shchild3, setShchild3] = useState(false);
const hideComponent = (varname) => {
switch (varname) {
case "shchild1":
setShchild1(!shchild1);
break;
case "shchild2":
setShchild2(!shchild2);
break;
case "shchild3":
setShchild3(!shchild3);
break;
default:
return;
}
};
return (
<div
style={{
width: "50%",
textAlign: "center",
margin: "auto",
marginTop: "50px"
}}
>
{shchild1 && <Child1 />}
<hr />
{shchild2 && <Child2 />}
<hr />
{shchild3 && <Child3 />}
<hr />
<div>
<button onClick={() => hideComponent("shchild1")}>
Click here to hide GFG child1 component
</button>
<button onClick={() => hideComponent("shchild2")}>
Click here to hide GFG child2 component
</button>
<button onClick={() => hideComponent("shchild3")}>
Click here to hide GFG child3 component
</button>
</div>
</div>
);
};
export default App;
JavaScript
// Filename - Child1.js
import React from "react";
const Child1 = () => {
return <div>This is how GFG child component number 1 looks like.</div>;
};
export default Child1;
JavaScript
// Filename - Child2.js
import React from "react";
const Child2 = () => {
return <div>This is how GFG child component number 2 looks like.</div>;
};
export default Child2;
JavaScript
// Filename - Child3.js
import React from "react";
const Child3 = () => {
return <div>This is how GFG child component number 3 looks like.</div>;
};
export default Child3;
Output:
Similar Reads
How to show and hide Password in ReactJS?
To show and hide passwords in React JS we can simply use the password input with an input to select the show and hide state. The user might need to see what has he used as the password to verify which is an important concept in login and registration forms. We can create this type of password input
3 min read
How to get an Element by ID in ReactJS ?
ReactJS, a popular JavaScript library for user interfaces, empowers developers with tools, such as the ref system, to manipulate the DOM by accessing elements using their unique IDs. This article explores the process of obtaining elements by ID in ReactJS for effective component interaction and mani
4 min read
How to bind event handlers in React?
Binding event handlers in React is a fundamental concept that ensures interactive and responsive web applications. React, a popular JavaScript library for building user interfaces uses a declarative approach to handle events. This article explores various methods to bind event handlers in React, hig
3 min read
How to use Fade Component in React JS ?
The Fade Component, available in Material UI for React, seamlessly adds a fade animation to a child element or component. Integrating this component into a React JS project is straightforward and enhances the user interface with ease.Prerequisites:React JSMaterial UIPopper Transitions: The Transitio
2 min read
How to create Switch in ReactJS?
In this article, we will learn how to create a switch in React that toggles between light and dark mode. We'll use Material-UI's Switch component to achieve this functionality. By the end of this guide, you'll be able to implement a theme switcher that allows users to seamlessly switch between light
2 min read
How to handle forms in React ?
In React, Form handling is one of the basic and important concepts that every developer should learn about. Forms are used to collect the data so that we can use the data for various purposes. This article, lets us understand form handling in React along with examples.Prerequisites:JSXReactuseStateF
6 min read
How to use Popper Component in ReactJS ?
A Popper is used to show the part of the content on top of another. It's an alternative feature for react-popper. Material UI for React has this component available for us, and it is simple and very easy to integrate. For perfect positioning, it uses 3rd party library which is Popper.js.Prerequisite
3 min read
How to use Portal Component in ReactJS ?
The portal component renders its children into a new subtree outside the current DOM hierarchy. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Portal Component in ReactJS using the following approach.Prerequisites:NodeJS or NPMReact JSMate
2 min read
How to create Tabs in ReactJS ?
Tabs make it easy to explore and switch between different views. Material UI for React has this component available for us and it is very easy to integrate. We can use Tabs Component in ReactJS using the following approach.Prerequisites:NPM & Node.jsReact JSMaterial UIwe have these approaches to
4 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read