$> man42.net Blog written by a human

# Issue

I ran into some issues regarding onMouseLeave behavior in React.

I was expecting onMouseLeave to be consistently called after receiving an onMouseEnter event. It's not always the case, there are some issues here and there.

I've run into some issues when setting up JavaScript scrolling animations, onMouseLeave was not called reliably (React 15.3.0, Chrome 51).

# Workaround

One workaround would be to use jQuery $.hover() which works more reliably.

However, I like to define my event handlers right on the element.

Here is the workaround I've settled with, still partially relying on jQuery:

  • Call $(event.currentTarget).one('mouseleave', handleMouseLeave) when onMouseEnter is triggered.
  • Do NOT set any onMouseLeave as its behavior is unreliable.

Note: We are using .one() here because we are just interested in the mouseleave event directly following the onMouseEvent call.

Code:

let Hover = React.createClass({
  render: function() {
    return (
      <span
        style={{ backgroundColor: '#00FFFF', padding: '8px' }}
        onMouseEnter={(event) => {
          console.log('enter');
          $(event.currentTarget).one('mouseleave', (event) => {
            console.log('leave');
          });
        }}>
        move your cursor here and check the console
      </span>
    );
  }
});

React.render(
  <Hover></Hover>,
  document.getElementById('container')
);

Example on jsfiddle: http://jsfiddle.net/kk91xk1v/

Buffer this pageShare on TumblrDigg thisShare on FacebookShare on LinkedInTweet about this on TwitterEmail this to someoneShare on Google+Share on RedditPin on Pinterest