theonlychase
8/1/2017 - 4:41 PM

Detect a click outside of a React Component

Detect a click outside of a React Component

componentDidMount() {
    document.addEventListener('click', this.handleClickOutside.bind(this), true);
  }

  componentWillUnmount() {
      document.removeEventListener('click', this.handleClickOutside.bind(this), true);
  }

  handleClickOutside(event) {
      const domNode = ReactDOM.findDOMNode(this);

      if ((!domNode || !domNode.contains(event.target))) {
          this.setState(prevstate => ({
              profileToggle: false
          }));
      }
  }