How to show hide component on Click in React JS?

In this examples ToggleBox component have a Show/Hide button which will Show or Hide the content of child component Vehicles.. You just need to replace the placeholder content of App.js and create two new files ToggleBox.js and Vehicles.js and update the contents as given below.


src\App.js
import React, { Component } from "react";
import ToggleBox from "./ToggleBox";
import Vehicles from "./Vehicles";

class App extends Component {
	render(){
		return (
			<ToggleBox title="Show Vehicles">
				<Vehicles />
			</ToggleBox>
		);
	}
}

export default App;

src\ToggleBox.js
import React, { Component } from "react";

class ToggleBox extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			opened: false,
		};
		this.toggleBox = this.toggleBox.bind(this);
	}
  
	toggleBox() {
		const { opened } = this.state;
		this.setState({
			opened: !opened,
		});
	}
  
	render() {
		var { title, children } = this.props;
		const { opened } = this.state;

		if (opened){
			title ='Hide Vehicles';
		}else{
			title ='Show Vehicles';
		}

		return (
			<div className="box">
				<div className="boxTitle" onClick={this.toggleBox}>
					{title}
				</div>
				{opened && (					
					<div class="boxContent">
						{children}
					</div>
				)}
			</div>
		);
	}
}

export default ToggleBox;

src\Vehicles.js
import React, { Component } from "react";

class Vehicles extends Component {	 
	render() {
		return (
			<div> Vehicles Child Component </div>
		);
	}
}

export default Vehicles;


Most Helpful This Week