简体   繁体   中英

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>
  );
}

PS- I'm using react-bootstrap for creating modal.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM