Here comes the simple, effective and best solution with a Classless React Component for show/hide the elements. Use of React-Hooks which is available in the latest create-react-app project that uses React 16 It sets the style attribute to display: none !important based on the hide or show props. One way could be to use React's ref and manipulate CSS class using the browser's API. Its benefit is to avoid rerendering in React if the sole purpose is to hide/show some DOM element on the click of a button.
return(
<nav className="nav__bar">
<ul className="menu">
<li className="menu__icon" onClick={() => setShow(currentShow => !currentShow)}>
<box-icon name='menu' color="floralwhite" size="md"/>
{ show ? <Curtain/> : null }
</li>
</ul>
</nav>
);
const Search = () => {
const [showResults, setShowResults] = React.useState(false)
const onClick = () => setShowResults(true)
return (
<div>
<input type="submit" value="Search" onClick={onClick} />
{ showResults ? <Results /> : null }
</div>
)
}
const Results = () => (
<div id="results" className="search-results">
Some Results
</div>
)
ReactDOM.render(<Search />, document.querySelector("#container"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<style type="text/css">
.hidden { display:none; }
</style>
Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: Step to Run Application: Run the application using the following command from the root directory of the project: Step 2:After creating your project folder i.e. foldername, move to it using the following command:cd foldername
npx create - react - app foldername
cd foldername
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;
Now it’s time to merge all these child JS files into the main parent file where we can set some particular conditions to show or hide some particular components. So let’s create the main file name App.js and paste the following code into it.
Now define three different boolean variables into the App.js file.
constructor() {
super();
this.state = {
name: "React",
shchild1: false,
shchild2: false,
shchild3: false
};
}
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;
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. 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. In this example, we have used props from the parent component and will show or hide the div conditionally using the same props.
1import React, { Component } from "react";
2
3class Demo1 extends Component {
4 constructor() {
5 super();
6 this.state = {
7 name: "React"
8 };
9 }
10
11 render() {
12 return <div>This is Demo1 component</div>;
13 }
14}
15
16export default Demo1;
1import React, { Component } from "react";
2
3class Demo2 extends Component {
4 constructor() {
5 super();
6 this.state = {
7 name: "React"
8 };
9 }
10
11 render() {
12 return <div>This is Demo2 component</div>;
13 }
14}
15
16export default Demo2;
1import React, { Component } from "react";
2
3class Demo3 extends Component {
4 constructor() {
5 super();
6 this.state = {
7 name: "React"
8 };
9 }
10
11 render() {
12 return <div>This is Demo3 component</div>;
13 }
14}
15
16export default Demo3;
1import React, { Component } from "react";
2import { render } from "react-dom";
3import Demo1 from "./Demo1";
4import Demo2 from "./Demo2";
5import Demo3 from "./Demo3";
6
7class App extends Component {
8 constructor() {
9 super();
10 this.state = {
11 name: "React",
12 showHideDemo1: false,
13 showHideDemo2: false,
14 showHideDemo3: false
15 };
16 this.hideComponent = this.hideComponent.bind(this);
17 }
18
19 hideComponent(name) {
20 console.log(name);
21 switch (name) {
22 case "showHideDemo1":
23 this.setState({ showHideDemo1: !this.state.showHideDemo1 });
24 break;
25 case "showHideDemo2":
26 this.setState({ showHideDemo2: !this.state.showHideDemo2 });
27 break;
28 case "showHideDemo3":
29 this.setState({ showHideDemo3: !this.state.showHideDemo3 });
30 break;
31 default:
32 null;
33 }
34 }
35
36 render() {
37 const { showHideDemo1, showHideDemo2, showHideDemo3 } = this.state;
38 return (
39 <div>
40 {showHideDemo1 && <Demo1 />}
41 <hr />
42 {showHideDemo2 && <Demo2 />}
43 <hr />
44 {showHideDemo3 && <Demo3 />}
45 <hr />
46 <div>
47 <button onClick={() => this.hideComponent("showHideDemo1")}>
48 Click to hide Demo1 component
49 </button>
50 <button onClick={() => this.hideComponent("showHideDemo2")}>
51 Click to hide Demo2 component
52 </button>
53 <button onClick={() => this.hideComponent("showHideDemo3")}>
54 Click to hide Demo3 component
55 </button>
56 </div>
57 </div>
58 );
59 }
60}
61
62render(<App />, document.getElementById("root"));
1
switch (name) {
2
case "showHideDemo1":
3 this.setState({
showHideDemo1: !this.state.showHideDemo1
});
4
break;
5
case "showHideDemo2":
6 this.setState({
showHideDemo2: !this.state.showHideDemo2
});
7
break;
8
case "showHideDemo3":
9 this.setState({
showHideDemo3: !this.state.showHideDemo3
});
10
break;
11
default:
12 null;
13
}
Let's see this in action! We will only display the rest of the product name if it has something to display: If you want to only display something if a value is true and there is nothing to display if the result is false, there is a shortcut rather than having null on the falsey side of a ternary operator. It involves using a conditional inside of your JSX that looks like checkIfTrue && <span>display if true</span>. Because if statements that use && operands stop as soon as they find the first value that evaluates to false, it won't reach the right side (the JSX) if the left side of the equation evaluates to false. We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here.
In modern React, a component is little more than a function whose job it is to return the value that is to be rendered. Just like regular functions, functional components can have multiple return values. If what the component renders is an "all or nothing" situation, the simplest way to control whether an element is rendered is to avoid returning any JSX at all, and return null
instead.
Because this if statement is not embedded inside of JSX but is just part of the regular JavaScript portion of the function, you are free to use any sort of JS construct that you like. In this example, if the product is not available, we're just going to return null
.
const AddToCart = ({ available }) => {
if (!available) return null;
return (
<div className="full tr">
<button className="product--cart-button">Add to Cart</button>
</div>
);
};
When you need to control whether one element vs. another is displayed, or even one element vs. nothing at all (null
), you can use the ternary operator embedded inside of a larger portion of JSX.
In this case, if there are no products remaining, we will display "Sold Out"; otherwise we will display the number of products remaining.
<div className="half">
<p>{description}</p>
{remaining === 0 ? (
<span className="product-sold-out">Sold Out</span>
) : (
<span className="product-remaining">{remaining} remaining</span>
)}
</div>
<h2>
<span className="product--title__large">{nameFirst}</span>
{nameRest.length > 0 && (
<span className="product--title__small">{nameRest.join(" ")}</span>
)}
</h2>
Up until this point we have chosen between rendering an element or not. What if we wanted to render an element but not have it seen? At this point we have a few options to focus on — the first being directly modifying the HTML element's style
property, setting CSS attributes such as display
and opacity
. In this short example below we will set the display
property to be either block
or none
depending on the value contained within showInfo
. Once again, a ternary operator is used inside embedded JSX to control the flow of our application.
<div style={{ display: showInfo ? "block" : "none" }}>info</div>
Along the same theme as modifying style
attributes, we can modify which class an element has, giving us the ability to control an element's display
, opacity
, or even hiding it off the side of the screen as might be done with a hamburger menu when it is in its closed state.
In the example below, the nav
element is off the left side of the screen with left: -200px
, but when the class open
is added to the nav
element, it transitions to having left: 0px
, and suddenly it is visible again.
nav {
position: fixed;
left: -200 px;
width: 200 px;
padding: 1 rem;
transition: 0.3 s all ease;
z - index: 1000;
height: 100 vh;
background: #cfd8dc;
}
nav.open {
left: 0 px;
}
To show and hide components in React you are going to need to conditionally render them. For the most part conditional rendering will be done by checking if a value passes a condition, just like in an if statement but for react components and JSX. But for most components, unless specifically built in as functionality, to show or hide them you will need to conditionally render them. In this post we will be covering how to show and hide components and elements in React with as little technical jargon as possible so you will have everything you need right here without having to look any further!
.example - properties {
display: none;
opacity: 0;
pointer - events: none;
visibility: none;
z - index: -1;
}
.lightbox {
position: absolute;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
transition: 0.3 s all;
opacity: 1;
pointer - events: auto;
z - index: 1;
}
.hide - lightbox {
opacity: 0;
pointer - events: none;
z - index: -1;
}
import React, { useState } from "react";
import "./base.css";
import "./lightbox.css";
export default function App() {
const [hideLightbox, setHideLightbox] = useState(true);
return (
<>
<button onClick={() => setHideLightbox(false)}>Show Lightbox</button>
<div className={`lightbox ${hideLightbox ? "hide-lightbox" : ""}`} />
</>
);
}
// React show/hide example on click
import React, { useState } from "react";
export default function App() {
const [hidden, setHidden] = useState(true);
return (
<div>
<h1> Hello World </h1>
{!hidden ? <p>You can see me!</p> : null}
<button onClick={() => setHidden(s => !s)}>
react show hide component
</button>
</div>
);
}
Similarly, you can use the ternary operator to show and hide elements in React, too. Alternatively, and perhaps more effectively, you can handle the visibility using the logical && operator — but from within the target component, instead of outside of it. The first step to controlling element or component visibility in React is to initialize a flag to track whether the element should actually be visible or not. It’s often cleaner and easier to read if you have a function that specifically handles these cases, rather than nesting many different conditions in one ternary statement or something similar.
Your component’s state should hold a boolean
value, such as isVisible
, which can be toggled (set to true
or false
) as per your own specific requirement and the business logic of the component:
const [isVisible, setIsVisible] = useState(true)
setIsVisible(false)
setIsVisible(true)
// Toggle whatever the current value is
setIsVisible(prevIsVisibleValue => !prevIsVisibleValue)
This is arguably the most common and most convenient approach.
We can simply use the logical and operator (&&
) to control visibility:
{isVisible && <h5>Some element</h5>}
This caveat is not limited to or specific to React.
Consider this example:
const isVisible = true
let age = 22
{isVisible && age && <h5>Your age is: {age}</h5>}
// outputs a h5 with text "Your age is 22"
This is just like the logical &&
operator example above, but you can also supply an else
expression to the statement:
{showAge ? <h5>Your age is {age}</h5> : <h3>Age hidden</h3>}
You can also control the visibility of an element with a simple CSS class, like so:
.element {
display: none;
}
.visible {
display: block;
}
While building React applications, we might come across cases where a React component needs to be toggled between show and hide states. Conditional rendering combined with a React State will allow us to show/hide components based on the Boolean value assigned to the state. First, we need to create a React component where the show/hide functionality will be implemented. In the code below, the Default component will display two lines of text enclosed in <h1> and <h2> tags. The show & hide functionality is more generic since the implementation is similar irrespective of the child component. Hence, we will create a wrapper component that can be reused by other multiple components rather than repeating the functionality every time.
import React from "react";
export default function Default() {
return (
<div className="default-container">
<h1>Welcome to React</h1>
<h2>Click below to toggle visiblity</h2>
</div>
);
}
In the code below, the wrapper component ToggleVisibility accepts a child component from props to include it in the JSX code.
export default function ToggleVisibility({ children }) {
return (
<div className="component-container">
{children}
</div>
);
}
The “show” state is declared to keep track of the component’s visibility. Every time setShow() function is called with the updated as the parameter, the ToggleVisibility component is re-rendered with updated state value.
const [show, setShow] = useState();
<button>{buttonText}</button>
The value of the React state is toggled simply by updating with “!show“. Therefore, every time toggleShow() function is called, the Boolean value of “show” state changes from true to false or vice versa.
function toggleShow() {
setShow(!show);
}
In the below examples, we use buttons that hide and show <div>My element</div> element. We use useState() hook to store the visibility state. One buton is used to display element and second one to hide the same element. In this article, we would like to show you how to show or hide elements in React. There are to three ways how to show or hide elements in React:
Quick solution:
import React, { useState } from 'react';
const App = () => {
const [visible, setVisible] = useState(false); // visibility state
// const showElement = () => setVisible(true);
// const hideElement = () => setVisible(false);
return (
<div>
{visible && <div>My element</div>}
</div>
);
};
When onClick
button event occurs we are able to set new visible
state with setVisible(!visible)
- clicks hide and show the element.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>{visible ? 'Hide' : 'Show'}</button>
{visible && <div>My element</div>}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<button onClick={() => setVisible(true)}>Show</button>
<button onClick={() => setVisible(false)}>Hide</button>
{visible && <div>My element</div>}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
className
property uses JSX construction. In this case the element is not removed - it is just invisible by styles.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [visible, setVisible] = React.useState(false);
return (
<div>
<style>{`
.element-visible { display: block }
.element-hidden { display: none }
`}</style>
<button onClick={() => setVisible(!visible)}>{visible ? 'Hide' : 'Show'}</button>
<div className={visible ? 'element-visible' : 'element-hidden'}>My element</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Similarly, we can use the same conditional operators to show or hide components. In this tutorial, we are going to learn about different ways to show or hide elements and components in react. In this example, we are rendering <HideButton> component if isActive property is true.If the property is false we are rendering <ShowButton> component. In the below example, we are using JavaScript if/else statement to show or hide elements.
import React,{Component} from 'react'
class App extends Component{
render(){
return(
<div>
<h1>Hello React</h1>
<button>Show</button> <button>Hide</button> </div>
)
}
}
export default App;
import React,{Component} from 'react'
class App extends Component{
state = {
isActive:false }
handleShow = ()=>{
this.setState({
isActive: true })
}
handleHide = () =>{
this.setState({
isActive: false })
}
render(){
return(
<div>
{this.state.isActive ? <h1>Hello React</h1> : null } <button onClick={this.handleShow}>Show</button>
<button onClick={this.handleHide}>Hide</button>
</div>
)
}
}
export default App;
<div>
{this.state.isActive && <h1>Hello React</h1>} <button onClick={this.handleShow}>Show</button>
<button onClick={this.handleHide}>Hide</button>
</div>
import React, { Component } from "react";
class App extends Component {
state = {
isActive: false
};
handleShow = () => {
this.setState({isActive: true});
};
handleHide = () => {
this.setState({isActive: false});
};
render() {
return (
<div>
{this.state.isActive && <h1>Hello react</h1>}
{this.state.isActive ?( <HideButton onClick={this.handleHide}/> ) : ( <ShowButton onClick={this.handleShow}/> )} </div>
)
}
}
export default App;