Create A Modal Popup Using ReactJS

Introduction

 
In this article, we are going to learn how to create a bootstrap modal popup in ReactJS.
 
Prerequisites
  • Basic knowledge of React
  • Visual Studio Code must be installed
  • Node JS must be installed

Create ReactJS project

 
Step 1
 
The very first step is to create a new React.js project using the following command:
  1. npx create-react-app reactmodal
Step 2
 
Open the newly-created project in Visual Studio code and install React bootstrap in this project using the following command:
  1. npm install react-bootstrap bootstrap  
Step 3
 
Now, open the index.js file and import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';   
Step 4
 
Next, open app.js then replace all of the code with the following:
  1. import React from 'react';  
  2. import './App.css';  
  3. import { Button,Modal} from 'react-bootstrap';  
  4. class App extends React.Component {  
  5.   constructor(){  
  6.     super();  
  7.     this.state={  
  8.       show:false  
  9.     }  
  10.   }  
  11.   handleModal(){  
  12.     this.setState({show:!this.state.show})  
  13.   }  
  14.   render(){  
  15.     return (  
  16.       <div>  
  17.         <h2 align='center'>Example of Modal in Reactjs</h2>  
  18.         <div className="modalClass">  
  19.           <Button onClick={()=>this.handleModal()}>Click To Open Modal</Button>  
  20.         </div>  
  21.           
  22.         <Modal show={this.state.show} onHide={()=>this.handleModal()}>  
  23.           <Modal.Header closeButton>This is a Modal Heading</Modal.Header>  
  24.           <Modal.Body>This is a Modal Body</Modal.Body>  
  25.           <Modal.Footer>  
  26.             <Button onClick={()=>this.handleModal()}>Close</Button>  
  27.             <Button onClick={()=>this.handleModal()}>Save</Button>  
  28.           </Modal.Footer>  
  29.         </Modal>  
  30.       </div>  
  31.     )  
  32.   }  
  33. }  
  34. export default App;  
 
Step 5
 
Open App.css file and paste the style.
  1. .modalClass {  
  2.   text-aligncenter;  
  3.   margin-top100px;  
  4. }  
Output
 
 

Conclusion

 
In this article, we have learned how to implement a bootstrap popup in ReactJS.
 
Please give your valuable feedback/comments/questions about this article.