0

Could you please help me with one issue? I'd like to make a closing modal window by clicking on backdrop (using ReactJS). But in result window is closing even i click on modal window (at any position).

Here is my code:

import React from "react";
import { Fragment } from "react";
import ReactDOM from "react-dom";

import "./_Modal.scss";

const Backdrop = (props) => {
  return (
    <div className="backdrop" onClick={props.onClose}>
      {props.children}
    </div>
  );
};

const ModalOverlay = (props) => {
  return <div className="modal">{props.children}</div>;
};

const portalItem = document.getElementById("overlays");

const Modal = (props) => {
  return (
    <Fragment>
      {ReactDOM.createPortal(
        <Backdrop onClose={props.onClose}>
          <ModalOverlay>{props.children}</ModalOverlay>
        </Backdrop>,
        portalItem
      )}
    </Fragment>
  );
};

export default Modal;

And here is CSS:

.backdrop {
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: 20;
    background-color: rgba(0,0,0, 0.7);
    display: flex;
    justify-content: center;
    align-items: flex-start;
    overflow: auto;
    padding-bottom: 15vh;
}

.modal {
    position: relative;
    max-width: 70%;
    top: 5vh;
    background-color: $darkgrey;
    padding: 1rem;
    border-radius: 1.5rem;
    box-shadow: 0 1rem 1rem rgba(0,0,0, 0.25);    
    z-index: 30;
}
}

I'm just start to learning frontend, therefore do not judge strictly )

AlexCap
  • 9
  • 2
  • Does this answer your question? [React close modal on click outside](https://stackoverflow.com/questions/59017954/react-close-modal-on-click-outside) – gloo Jun 30 '22 at 17:26
  • Thank you very much!!! Just for understanding other people: after adding event.stopPropagation() in ModalOverlay. – AlexCap Jun 30 '22 at 19:21

1 Answers1

0

Just for understanding other people: after adding event.stopPropagation() in ModalOverlay everything works!

const ModalOverlay = (props) => {
  return (
    <div
      className="modal"
      onClick={(event) => {
        event.stopPropagation();
      }}
    >
      {props.children}
    </div>
  );
};
AlexCap
  • 9
  • 2