L
L
lexstile2019-05-07 16:06:39
JavaScript
lexstile, 2019-05-07 16:06:39

How to correctly handle a click outside of a component in react js?

Current code:

componentWillMount() {
    document.addEventListener('click', this.onClickOuterModal, false);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.onClickOuterModal, false);
  }

  onClickOuterModal = (event) => {
    const modal = document.getElementsByClassName('modal');
    if (modal !== event.target) {
      this.props.closeModal();
    }
  };

1. Can it be processed somehow more elegantly and should it be done?
2. How to make the check also on click on the child elements of the component? (now on a click inside the modal window it closes - it shouldn't).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-05-07
@lexstile

if (!modal.contains(event.target)) {
  this.props.closeModal();
}

Element in a good way to receive through ref.

K
kova1ev, 2019-05-07
@kova1ev

need to use portals

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question