Show an Element on Hover in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Show an Element on Hover in React #

To show an element on hover in React:

  1. Set the onMouseOver and onMouseOut props on the element.
  2. Track whether the user is hovering over the element in a state variable.
  3. Conditionally render the other element based on the state variable.
App.js
import {useState} from 'react'; const App = () => { const [isHovering, setIsHovering] = useState(false); const handleMouseOver = () => { setIsHovering(true); }; const handleMouseOut = () => { setIsHovering(false); }; return ( <div> <div> <div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}> Hover over me </div> {isHovering && ( <div> <h2>Only visible when hovering div</h2> </div> )} </div> </div> ); }; export default App;

show element on hover

We set the onMouseOver prop on the div element, so every time the user hovers over the element, the handleMouseOver function is invoked.

The mouseover event is triggered when the user moves their cursor onto the element or one of its child elements.

In our handleMouseOver function, we simply set the isHovering state variable to true.

Conversely, in our handleMouseOut function, we set the state variable to false.

The mouseout event is triggered when the user's cursor is no longer contained within the element or one of its children.

We used the logical AND (&&) operator to conditionally render the other div element.

The logical AND (&&) operator returns the value to the left if it's falsy, otherwise the value to the right is returned.

If the state variable stores a false value, the logical AND (&&) operator would return false and nothing would get rendered.

Booleans, null and undefined are ignored. They simply don't render.

When the user hovers over the div element:

  1. The handleMouseOver function is invoked.
  2. The isHovering state variable is set to true.
  3. The other div element gets rendered.

Conversely, when the user moves their cursor out of the div element:

  1. The handleMouseOut function is invoked.
  2. The isHovering state variable is set to false.
  3. The other div element is no longer shown.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.