Show text when hovering over an Element in React

avatar

Borislav Hadzhiev

Tue Apr 26 20222 min read

Show text when hovering over an Element in React #

To show text when hovering over an element 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 text 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 me </div> {isHovering && <h2>Hello world</h2>} </div> </div> ); }; export default App;

on hover show text

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 text when the div is hovered.

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 h2 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 h2 element is no longer shown.
Use the search field on my Home Page to filter through my more than 1,000 articles.