In this guide, you will see how to handle hover events, one of the most common user interactions in web apps.
The library does not have built-in onHover event, but there is a way to handle hovering events in React.
To implement this feature, you need two event handlers - onMouseEnter to handle the when the mouse enters borders of the element, and onMouseLeave to handle when the mouse leaves. Handling these two events ensures that hover event handler works consistently.
Now let’s explore potential use-cases for onHover in React.
In our first example, let’s set onMouseEnter and onMouseLeave handlers to show or hide a component when user hovers over the element.
function App() {
const [hidden, setHidden] = useState(true);
return (
<div
className="container"
onMouseEnter={() => setHidden(false)}
onMouseLeave={() => setHidden(true)}
>
{hidden ? null : <h1>Hovering</h1>}
</div>
);
}
In this example, we have a state variable hidden
, and its value is a boolean. Inside JSX, we look at the boolean value to conditionally render a header that says ‘Hovering’.
onMouseEnter and onMouseLeave event handlers are set on a div. onMouseEnter event sets hidden
to false
, so the header text appears. onMouseLeave
sets it to true
, so when the mouse leaves the div
, the header text hides again.
Here’s a
to illustrate howonMouseEnter
and onMouseLeave
can replicate an onHover
event handler in React.
-
As you can see, the hovering effect activates even if your mouse is on the element’s border.
If you liked this guide, SimpleFrontEnd blog has many similar React guides with examples.
Similar to conditional rendering, you canuse onMouseEnter and onMouseLeave event handlers to conditionally style elements in React.
To be more specific, event handlers update the state, which we can use to conditionally apply styles in JSX.
function App() {
const [warning, setWarning] = useState(true);
return (
<div
className="container"
onMouseEnter={() => setWarning(false)}
onMouseLeave={() => setWarning(true)}
>
<h1 style={{ color: warning ? "goldenrod" : "green" }}>
Please hover over the container{" "}
</h1>
</div>
);
}
In this example, onMouseEnter and onMouseLeave event handlers update warning
state variable. Which we use to change color of the text in the container.
You can also think of this as a programmatic alternative to using the :hover selector in CSS.