Search code examples
javascriptreactjsbootstrap-modalreact-bootstrap

[RESOLVED]How to cancel "bootstrap modal" exit behavior?


I need to validate data (eg. fill up all of the fields in the form) before users intend to close the modal via close-button or backdrop-area.

If it's valid then let the exit process going otherwise cancel it.

<Modal show={isShow} keyboard={false} >
  <Modal.Header>
    <Modal.Title>Profile</Modal.Title>
    <CloseButton onClick={onClose} />
  </Modal.Header>
  <Modal.Body>
    {...}
  </Modal.Body>
</Modal>

It's possible to do this in React?


Solution

According to Modal#onHide description, I listen to the onHide then validate data before close it.

const onModalHide = () => {
  if (validateData()) setIsShow(false);
};
<Modal show={isShow} onHide={onModalHide} >
  <Modal.Header>
    <Modal.Title>Profile</Modal.Title>
  </Modal.Header>
  <Modal.Body>
    {...}
  </Modal.Body>
</Modal>

Solution

  • You will need to manually select the modal id and listen on hide.bs.modal event

    You are using bootstrap so probably already import jquery so:

    $('#myModal').on('hide.bs.modal', function (e) {
       if (!validated) return e.preventDefault() 
    })
    

    Or with js:

    document.addEventListener('hide.bs.modal', function(e) {
        if (event.target.id == 'myModal') {
          if (!validated) return e.preventDefault();
        }
    });