Close the overlay only if we click outside the modal content

Viewed 1012

I have a modal that is created using styled-components. It is wrapped with an overlay. When I click the overlay the modal closes itself, but when I click the modal's content it also closes. The idea is to close the overlay only if we go outside the (box/content). I believe it has something to do with the CSS. How can we fix this?

In order to be able to reproduce the issue I've created a sandbox: https://codesandbox.io/s/zen-cache-q5w0n

1 Answers

You could define an onClick on the ModalBody component and use event.stopPropagation.

stopPropagation according to mdn:

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.

Adjusted version of your Modal component:

export const Modal: React.FC<ModalProps> = (props) => {
  return (
    <div>
      {props.isOpened && (
        <Overlay hide={props.hideModal}>
          <ModalContainer>
            <ModalPosition>
              <div className={"w-100"}>
                <ModalBody onClick={e => e.stopPropagation()}>{props.children}</ModalBody>
              </div>
            </ModalPosition>
          </ModalContainer>
        </Overlay>
      )}
    </div>
  );
};
Related