How to open or close react-bootstrap modal pro-grammatically?
Last Updated :
16 Jul, 2020
A modal is a pop-up or a dialog box that is placed on the current page to display the message that needs to be read. Using the react-bootstrap UI library, we will program the modal using hooks in a functional component.
We can use the useState() hooks to open/close a react-bootstrap modal . The useState function is a built in hook that allows us to add state to a functional component without switching to a class component.
Syntax:
const [state, setState] = useState(initialState);
The first value state represents the current state whereas the second value is used to update the state of a function. The useState function takes an argument as the default value. Before proceeding further there is one prerequisite.
Prerequisite:
- Installed react-bootstrap:
npm install react-bootstrap bootstrap
- Import bootstrap.min.css:
import 'bootstrap/dist/css/bootstrap.min.css';
- Import built-in hook useState:
import React, {useState} from "react";
- Import individual components such as Button and Modal
import Button from 'react-bootstrap/Button';
App.js:
javascript
import React, {useState} from "react" ;
import Button from 'react-bootstrap/Button' ;
import Modal from 'react-bootstrap/Modal' ;
function Example() {
const [show, setShow] = useState( false );
const handleClose = () => setShow( false );
const handleShow = () => setShow( true );
return (
<>
<Button variant= "primary" onClick={handleShow}>
Launch static backdrop modal
</Button>
<Modal
show={show}
onHide={handleClose}
backdrop= "static"
keyboard={ false }
>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
I will not close if you click outside me.
Don't even try to press
escape key.
</Modal.Body>
<Modal.Footer>
<Button variant= "primary" onClick={handleClose}>
Close
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default Example;
|
index.js:
javascript
import React from "react" ;
import ReactDOM from "react-dom" ;
import 'bootstrap/dist/css/bootstrap.min.css' ;
import App from "./App" ;
const rootElement = document.getElementById( "root" );
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...