React Mouse onHover Event with Example
The onHover event handler does not exist in React. But React provides event handlers to detect hover state for an element. In this article, we are going to learn how to use the handlers.
Table of Contents
Show and Hide Content
On hover an element, we can take an action. I’m going to show & hide content on hover a button. To do this, we’ll use 2 event handlers:
- onMouseEnter
- onMouseLeave
Let’s have a look at the example:
import React, { useState } from 'react';
import './App.css';
function App() {
const [isShownHoverContent, setIsShownHoverContent] = useState(false);
return (
<div className="App">
<button
onMouseEnter={() => setIsShownHoverContent(true)}
onMouseLeave={() => setIsShownHoverContent(false)}>
Hover!
</button>
{isShownHoverContent && (
<div>
It works..!
</div>
)}
</div>
);
}
export default App;
Now if we hover the button, It works..!
text will appear.
Change Background Color
In this example, we’re going to change background color of a div of mouse hover. Have a look:
import React from 'react';
import './App.css';
function App() {
function changeBackgroundColor(e) {
e.target.style.background = 'green';
}
return (
<div className="App">
<div onMouseOver={changeBackgroundColor}>Hover me!</div>
</div>
);
}
export default App;
There are two more hoverable event handlers named onMouseOut and onMouseLeave. You can test these.
That’s it. Thanks for reading.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.