How to handle hover events in your React Components

Sometimes, you'll have to perform some actions when a user hovers over an element. Most cases, using css :hover tag will do for this, but what about more complex actions? Such as switching text or changing entire components?

For this, you can use Reacts onMouseEnter and onMouseLeave properties:

        onMouseEnter={() => setText("You hovered over me!")}
        onMouseLeave={() => setText("Hover over me to see changes")}

Both these properties accept a function, so we can do whatever we want here. I've used inline functions in my examples, but you can easily call another function from somewhere else.

Checkout this code sandbox!

This is part of the React bite-size series of posts. Check out the rest here!