Allan Hortle Allan Hortle - 13 days ago 7
React JSX Question

How to listen for click events that are outside of a component

I want to close a dropdown menu when a click occurs outside of the dropdown component.

How do I do that?

Answer

In the element I have added mousedown and mouseup like this:

onMouseDown={this.props.onMouseDown} onMouseUp={this.props.onMouseUp}

Then in the parent I do this:

componentDidMount: function () {
    window.addEventListener('mousedown', this.pageClick, false);
},

pageClick: function (e) {
  if (this.mouseIsDownOnCalendar) {
      return;
  }

  this.setState({
      showCal: false
  });
},

mouseDownHandler: function () {
    this.mouseIsDownOnCalendar = true;
},

mouseUpHandler: function () {
    this.mouseIsDownOnCalendar = false;
}

The showCal is a boolean that when true shows in my case a calendar and false hides it.

Comments