MUI ClickAwayListener closing the modal itself when clicked (React.Js)

Viewed 1414

The required functionality for modal is that when clicked on the 'More' button, it should be visible and when either the More button or any other part of the screen is clicked (excluding the modal itself), the modal should be closed. I have tried various ways starting from https://usehooks-typescript.com/react-hook/use-on-click-outside & MUI's ClickAwayListener.

<ClickAwayListener
  onClickAway={handleClickAway}
>
  <div style={{ position: 'relative' }}>
    <button
      onClick={(e: any) => {
        e.stopPropagation();
        setModalVisible(!modalVisible);
      }}
    >
      More
    </button>
    <Modal
      visible={modalVisible}
      id="btn-container"
    >
        {dummy.map((str: string) => {
          return <span>{str}</span>;
        })}
    </Modal>
  </div>
</ClickAwayListener>
const handleClickAway = (e: any) => {
    if (e.target.localName === 'body') {
      e.preventDefault();
      return;
    }

    setModalVisible(false);
  };
const Modal = styled.div`
  position: absolute;
  top: 30px;
  left: -200px;
  background: #fff;
  padding: 25px;
  z-index: 8;
  visibility: ${({ visible }) => (visible ? 'visible' : 'hidden')};
  box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2);
  width: 250px;
  max-height: 320px;
  overflow-y: auto;
`;

Basically, the ClickAwayListener is not able to detect it's child component and is closing the modal even when I click inside the modal which should not be the functionality.

'Modal' component used here isn't a materialui component, it's a styled component that I built myself

1 Answers
  1. Use onBackdropClick in Modal instead of onClickAway, onBackdropClick fires when you clicks outside the Modal
<Modal onBackdropClick={() => setOpen(false)}
  1. Use onClose in Modal instead of onBackdropClick, onClose fires when the Modal want to close itself
<Modal onClose={(_, reason) => reason === 'backdropClick' && setOpen(false)}
  1. Use Dialog instead of Modal. Dialog is the component containing the Modal with good default styles out-of-the-box while Modal is its ugly cousin used for low level customization.
<Dialog onClose={(_, reason) => reason === 'backdropClick' && setOpen(false)}
Related