Pranay kumar
Pranay kumar

Reputation: 2197

Bootstrap modal didn't close while clicking outside of modal in React

I used a react-bootstrap modal to show notification in React. It works fine but it didn't close when I click outside of the modal.

Modal code


import React from "react";
import ReactDom from 'react-dom';
import Modal from "react-bootstrap/Modal";
import ModalBody from "react-bootstrap/ModalBody";
import ModalHeader from "react-bootstrap/ModalHeader";
import ModalFooter from "react-bootstrap/ModalFooter";
import ModalTitle from "react-bootstrap/ModalTitle";
import 'bootstrap/dist/css/bootstrap.css';

class ForgetPassword extends React.Component{
    constructor(props)
    {
        super(props);
        this.state={
            modalIsOpen:true

        }
    }
    render()
    {
        return (
            <Modal show={this.state.modalIsOpen}>
              <ModalHeader>
                <ModalTitle>Hi</ModalTitle>
              </ModalHeader>
              <ModalBody>asdfasdf</ModalBody>
              <ModalFooter>This is the footer</ModalFooter>
            </Modal>
          );
    }
}
  
export default ForgetPassword;




Upvotes: 0

Views: 1132

Answers (2)

rotimi-best
rotimi-best

Reputation: 1922

You don't have toggle set on the Modal component. You need to add the toggle prop to <Modal>, giving it a function, which when triggered, will toggle the value of the IsOpen in prop.

import React from "react";
import Modal from "react-bootstrap/Modal";
import ModalBody from "react-bootstrap/ModalBody";
import ModalHeader from "react-bootstrap/ModalHeader";
import ModalFooter from "react-bootstrap/ModalFooter";
import ModalTitle from "react-bootstrap/ModalTitle";
import 'bootstrap/dist/css/bootstrap.css';

class ForgetPassword extends React.Component{
  state = {
    modalIsOpen: true
  }

  toggleModal = () => {
    this.setState(prevState => ({
      modalIsOpen: !prevState.modalIsOpen
    }));
  };

  render() {
    return (
      <Modal show={this.state.modalIsOpen} onHide={this.toggleModal}>
        <ModalHeader>
          <ModalTitle>Hi</ModalTitle>
        </ModalHeader>
        <ModalBody>asdfasdf</ModalBody>
        <ModalFooter>This is the footer</ModalFooter>
      </Modal>
    );
  }
}

export default ForgetPassword;

Source

Upvotes: 2

Xerith
Xerith

Reputation: 322

The bootstrap react docs make reference to the onHide prop that should be on the modal - A callback fired when the header closeButton or non-static backdrop is clicked. Required if either are specified.

You will want to use this to set the show modal state as false, probably through a function.

Upvotes: 0

Related Questions