How to add inline CSS styles on Hover in React

avatar

Borislav Hadzhiev

Sun May 01 20222 min read

banner

Photo by Cody Black

Add inline CSS styles on Hover in React #

To add inline CSS styles on hover in React:

  1. Set the onMouseEnter and onMouseLeave props on the element.
  2. When the user hovers over or out of the element, update a state variable.
  3. Conditionally set inline styles on the element.
App.js
import {useState} from 'react'; const App = () => { const [isHovering, setIsHovering] = useState(false); const handleMouseEnter = () => { setIsHovering(true); }; const handleMouseLeave = () => { setIsHovering(false); }; return ( <div> <div> <div style={{ backgroundColor: isHovering ? 'salmon' : '', color: isHovering ? 'white' : '', }} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > Hover me </div> </div> </div> ); }; export default App;

react hover inline styles

We set the onMouseEnter and onMouseLeave props on a div element.

The mouseenter event is triggered when the user's mouse is moved within the element.

Conversely, the mouseleave event is triggered when the user's mouse is moved out of the element.

Every time the user hovers over the div, the handleMouseEnter function is invoked.

And every time they move their cursor out of the element, the handleMouseLeave function is invoked.

All we did in the 2 event handlers is update a state variable that tracks whether the user is hovering over the element.

We can then use a ternary to set inline styles on the element conditionally.

App.js
<div style={{ backgroundColor: isHovering ? 'salmon' : '', color: isHovering ? 'white' : '', }} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > 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 set the backgroundColor property to salmon, otherwise we set it to an empty string.

When the user hovers over the element:

  1. The handleMouseEnter function is invoked.
  2. The isHovering state variable is set to true.
  3. We conditionally set inline styles on the element.

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

  1. The handleMouseLeave function is invoked.
  2. The isHovering state variable is set to false.
  3. We revert the element's styles.
Use the search field on my Home Page to filter through my more than 1,000 articles.