react

How to use react-bootstrap modal in React


In this article, you will learn about how to use the react-bootstrap modal in react.

In react, a modal is nothing but a message box that is visible on the top of the screen of a webpage. You may familiar with the alert() message that is displayed on the top of your screen. But if you notice the message box was not so interactive with alert(). In react, you can easily create a beautiful modal by using react-bootstrap that will be more interactive and easy to use. In this article, we will discover how we can create a modal with the help of react-bootstrap. To do so you need to install bootstrap and react-bootstrap in your local machine where the react project is located. Let’s see the NPM command of installing these libraries in the below section

npm install react-bootstrap 
npm install bootstrap

// or

npm install react-bootstrap bootstrap

Here, you may install it separately or together by giving this NPM command. After installing these libraries we may be able to use them in our project. Let’s see the below code example of the react-bootstrap modal.

import React,{useState} from 'react';
import {Modal, Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  const [visible, setVisible] = useState(false);

  const btnClose = () => setVisible(false);
  const btnShow = () => setVisible(true);

  return (
    <>
      <Button variant="primary" onClick={btnShow}>
        Click Me To See Modal
      </Button>

      <Modal show={visible} onHide={btnClose}>
        <Modal.Header closeButton>
          <Modal.Title>Greetings</Modal.Title>
        </Modal.Header>
        <Modal.Body>Welcome! To Our Website. You will learn react-bootstrap                      modal.</Modal.Body>
        <Modal.Footer>
          <Button variant="danger" onClick={btnClose}>
            Close
          </Button>
          <Button variant="success" onClick={btnClose}>
            Save
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

export default App;

Here, you can see that we are simply importing our required react and others that will be used to make this program successful. Then we take two callback functions and they will be triggered based on the button that has been clicked by the user. Let’s see the output below if things are working perfectly or not.

You can see that we are getting a beautiful modal the moment we have clicked on the button. The greetings modal will be invisible when we have clicked on any button of this modal. This is how you can create a modal by using react-bootstrap in React. Moreover, you can also create a custom modal and add too much functionality to it. It is not possible to demonstrate all of them in one article but the process of creating a modal is almost the same. To get more information you may visit the official site of the react-bootstrap modal


Share on social media

//