Introduction
In this ReactJS article, we learn how to hide and show a DOM element. When we click on a button, the element will hide from the DOM and after clicking it again it will show again, so it will give a toggle effect.
What is ReactJS?
React is an open-source JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.
Prerequisites
- Basic knowledge of React
- Visual Studio Code must be installed
- Node JS must be installed
Create ReactJS project
The very first step is to create a new React.js project using the following command:
- npx create-react-app reactHideShow
Step 2
Open the newly-created project in Visual Studio code and install React bootstrap in this project using the following command:
Step 3
Now, open the index.js file and import Bootstrap.
- import 'bootstrap/dist/css/bootstrap.min.css';
Step 4
The next step is to open App.js and paste the below code:
- import React from 'react';
- import './App.css';
- import { Button,Modal} from 'react-bootstrap';
- class App extends React.Component {
- constructor(){
- super();
- this.state={
- show:true,
- buttonName:"Hide Message"
- }
- }
-
- render(){
- return (
- <div>
- <div class="col-12 col-md-12">
- <div class="card">
- <div class="card-header">
- Example of hide and show
- <a onClick={()=>{this.setState({show:!this.state.show})}} class="btn btn-primary"><i
- className='fa fa-minus-square-o'></i> {this.state.show ? this.state.buttonName:'Show Message'}</a>
-
- </div>
- {
- this.state.show ?
- <div>
- <p><b>What is Lorem Ipsum?</b><br/>
- Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
- </div>
- :
- null
- }
-
- </div>
- </div>
- </div>
- )
- }
- }
- export default App;
Output
Conclusion
In this article, we have seen hide and show a DOM element in ReactJS.
Please give your valuable feedback/comments/questions about this article.