Allan Hortle Allan Hortle - 1 year ago 92
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 Source

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) {

      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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download