Created
November 13, 2018 14:10
-
-
Save jakewtaylor/c07573ec5f6a9ea66cb704b8e46eebd3 to your computer and use it in GitHub Desktop.
useMouseCoordinates()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Tooltip = (props) => { | |
const [x, y] = useMouseCoordinates(); | |
return ( | |
<p>Mouse is at x: {x}, y: {y}.</p> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
export const useMouseCoordinates = () => { | |
const [x, setX] = useState(0); | |
const [y, setY] = useState(0); | |
const handleMouseMove = (e) => { | |
setX(e.pageX); | |
setY(e.pageY); | |
}; | |
useEffect(() => { | |
window.addEventListener('mousemove', handleMouseMove); | |
return () => window.removeEventListener('mousemove', handleMouseMove); | |
}); | |
return [x, y]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment