DEV Community

NasreenKhalid
NasreenKhalid

Posted on

Create modal with Reactstrap

Image descriptionModals are a great way to display input forms or display any alert/notification/message to the users.
Today, we will use the react-bootstrap library to display a sign-in form and try to add different controls to open/close the modal on user actions.
Let's start by creating a new react app by typing in the following command:

npx create-react-app modal_app
Enter fullscreen mode Exit fullscreen mode

After the react app is created, we will install reactstrap and bootstrap in our project using the following command:

npm install reactstrap bootstrap
Enter fullscreen mode Exit fullscreen mode

Now we will write the code to open the modal in App.js file which will look like this:

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import {
    Button, Modal, ModalFooter,
    ModalHeader, ModalBody
} from "reactstrap"

function App() {

    // Modal open state
    const [modal, setModal] = React.useState(false);

    // Toggle for Modal
    const toggle = () => setModal(!modal);

    return (
        <div style={{
            display: 'block', width: 700, padding: 30
        }}>
            <h4>ReactJS Reactstrap Modal Component</h4>
           <Button color="danger" onClick={toggle}>
        Click Me
      </Button>
            <Modal isOpen={modal}
                toggle={toggle}
                modalTransition={{ timeout: 2000 }}>
                <ModalBody>
                     Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
                </ModalBody>
          <ModalFooter>
          <Button color="primary" onClick={toggle}>
            Do Something
          </Button>{' '}
          <Button color="secondary" onClick={toggle}>
            Cancel
          </Button>
        </ModalFooter>
            </Modal>
        </div >
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We have added two buttons 'Do Something' and 'Cancel' in the footer of the modal for more user interactivity.

Modals look nice and gives a good look to our user interfaces. Hope you can use this modal in your future projects.

Happy coding...

Top comments (0)