const div_ref = useRef();
<div ref={div_ref} />
What are the properties of div_ref
that I can use to find out if the mouse is hovering over div_ref
?
const div_ref = useRef();
<div ref={div_ref} />
What are the properties of div_ref
that I can use to find out if the mouse is hovering over div_ref
?
-
3
Why are you bothering with a
ref
? Why can't you just add amouseover
listener to the element? – Andy Commented Feb 20, 2022 at 21:05
1 Answer
Reset to default 4You can use the onMouseEnter() listener in React to know when an element is being hovered with the mouse. For example, if you wanted to show a text in React when you hover over a heading (or any other element), you would use the following code:
import React, { useState } from 'react';
function App() {
const [visible, setVisible] = useState(false); // initiate it at false
return (
<div>
<h2
onMouseEnter={() => setVisible(true)}
onMouseLeave={() => setVisible(false)}>
Move Mouse Towards Me
</h2>
{visible && ( // you can use "&&" since there is no else in this case
<div>Text to show</div>
)}
</div>
);
}
export default App;