Stan
Stan

Reputation: 153

React mouse events fired on components not listening for them

Not sure if it's my profound misunderstanding of React events or an actual bug, but mouse events registered on the parents sometimes fire on the children.

In the bin below, mousing around the two divs will eventually result in the inner div getting highlighted red, even though it doesn't have an event trigger for attaching the ui-hover class (though its parent does).

http://jsbin.com/vemopo/1/edit?css,js,output

Upvotes: 1

Views: 2577

Answers (1)

Adam Stone
Adam Stone

Reputation: 2006

It seems to depend on how fast the mouse is moving. My guess is, event.target becomes whatever is under the mouse when the event is triggered. So it fires when entering the parent div, but if the mouse is moving quickly then it may already be hovering the child div when the event handler is processed.

(Updated answer)

As @Stan commented, replacing event.target with event.currentTarget is the simplest fix, it will target the element whose listener triggered the event rather than the element under the mouse.

(Original answer / other options)

You can also set ref="target" on the parent div and then use the ref rather than the event target.

_mouseEnter: function(event) {
  this.refs.target.getDOMNode().classList.add('ui-hover');
},

However, it may be preferable to avoid touching the DOM like this. In that case you could use setState in the event handlers and use conditionals to give a different result depending on this.state.

_mouseEnter: function(event) {
  this.setState({
    hovering: true
  });
}

Upvotes: 1

Related Questions