Borislav Hadzhiev
Sun May 01 2022·2 min read
Photo by Cody Black
To add inline CSS styles on hover in React:
onMouseEnter
and onMouseLeave
props on the element.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;
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.
We can then use a ternary to set inline styles on the element conditionally.
<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.
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:
handleMouseEnter
function is invoked.isHovering
state variable is set to true
.Conversely, when the user moves their cursor out of the element:
handleMouseLeave
function is invoked.isHovering
state variable is set to false
.