Add a Class on hover in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Add a Class on hover in React #

To add a class 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 add the class based on the state variable.
App.js
import './App.css'; import {useState} from 'react'; const App = () => { const [isHovering, setIsHovering] = useState(false); const handleMouseOver = () => { setIsHovering(true); }; const handleMouseOut = () => { setIsHovering(false); }; return ( <div> <div> <div className={isHovering ? 'bg-salmon' : ''} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} > Hover me </div> </div> </div> ); }; export default App;

And here is the App.css file for the example.

App.css
.bg-salmon { background-color: salmon; color: white; }

add class 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 a ternary operator to conditionally add the class to the element.

App.js
<div className={isHovering ? 'bg-salmon' : ''} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} > Hover me </div>

The ternary operator is very similar to an if/else statement.

It checks if the value to the left of the question mark is truthy, and if it is, the operator returns the value to the left of the colon, otherwise the value to the right is returned.

In other words, if the isHovering variable stores a true value, we add the bg-salmon class to the element, otherwise return an empty string.

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 class gets added to the element.

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 class doesn't get added to the element.
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.