godon019
7/30/2019 - 2:23 AM

close when click outside of modal

side note: Close when click outside of modal - ref

class Modal extends Component {
  private modalRef = createRef;

  closeModal = (e) => {
    const { modalProps } = this.props;
    const node = this.modalRef.current;
    // ignore if click is inside the modal
    if (node && node.contains(e.target)) {
      return;
    }

    modalProps.hideModal();
  };

  componentDidMount() {
    document.addEventListener("mousedown", this.closeModal, false);
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.closeModal, false);
  }

  render() {
    const { modalProps, title, children } = this.props;
    return modalProps.show ? (
      <StyledModalOverlay>
        <StyledModal ref={this.modalRef}>
          <header>{title}</header>
          {children}
        </StyledModal>
      </StyledModalOverlay>
    ) : null;
  }
}