Yogesh Yadav
Yogesh Yadav

Reputation: 863

event.stopPropagation() not working on bootstrap modal

When clicking on modal window body, it runs outer div's onClick handler. event.stoppropagation() working fine for button inside outer div and buttons inside modal but don't know how to unbind outer div click handler on modal body.

sample code (Modal is not working on csb, please run on your code editor)

import React, { useState } from "react";
import { Button, Modal } from "react-bootstrap";

export default function App() {
  const [show, setShow] = useState(false);

  const handleShow = (event) => {
    event.stopPropagation();
    setShow(true);
  };

  const handleClose = (event) => {
    event.stopPropagation();
    setShow(false);
  };

  const deleteModal = () => {
    return (
      <Modal
        id="deleteModal"
        className="modal"
        show={show}
        onHide={handleClose}
        centered
        size="sm"
        backdrop="static"
        keyboard={false}
      >
        <Modal.Body>
          <div>
            <span>Delete Tweet ?</span>
          </div>
          <div>This can’t be undone</div>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Cancel
          </Button>
          <Button variant="primary">Delete</Button>
        </Modal.Footer>
      </Modal>
    );
  };

  const postHandler = () => {
    alert("clicked on div");
  };

  return (
    <div onClick={postHandler} style={{ border: "1px solid" }}>
      {deleteModal()}
      <h1>Hello CodeSandbox</h1>
      <Button variant="info" onClick={handleShow}>
        Delete
      </Button>
    </div>
  );
}

P.S- I'm using react-bootstrap for creating modal.

Upvotes: 4

Views: 2162

Answers (1)

Tarun Singh
Tarun Singh

Reputation: 480

 return (
    <>
      {show && deleteModal()}    // just move this logic outside the div
      <div onClick={postHandler} style={{ border: '1px solid' }}>
        <h1>Hello CodeSandbox</h1>
        <Button variant="info" onClick={handleShow}>
          Delete
        </Button>
      </div>
    </>
  );

Hey, if you just move the deleteModal outside the div then it would solve your problem.

Upvotes: 1

Related Questions