Borislav Hadzhiev
Tue Apr 26 2022·2 min read
Photo by Chris Ainsworth
To add a class on hover in React:
onMouseOver
and onMouseOut
props on the element.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.
.bg-salmon { background-color: salmon; color: white; }
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.
<div className={isHovering ? 'bg-salmon' : ''} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} > 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 add the
bg-salmon
class to the element, otherwise return an empty string.
When the user hovers over the div
element:
handleMouseOver
function is invoked.isHovering
state variable is set to true
.Conversely, when the user moves their cursor out of the div
element:
handleMouseOut
function is invoked.isHovering
state variable is set to false
.