visit
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.
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.
Similar to conditional rendering, you canuse onMouseEnter and onMouseLeave event handlers to conditionally style elements in React.
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.