Last active
September 15, 2020 10:33
-
-
Save imp-dance/cf49f52fe0ba998821c4f07885ee8942 to your computer and use it in GitHub Desktop.
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 React, { useState } from "react"; | |
const getTotalOffset = (el: HTMLElement) => { | |
let a: any = el, | |
x = 0, | |
y = 0; | |
while (a) { | |
x += a.offsetLeft; | |
y += a.offsetTop; | |
a = a.offsetParent; | |
} | |
return { offsetX: x, offsetY: y }; | |
}; | |
function useMouseMove( | |
reference: React.RefObject<HTMLElement> | |
): [(e: React.MouseEvent) => void, React.CSSProperties] { | |
const [mousePointer, setMousePointer] = useState({ x: 0, y: 0 }); | |
const mouseMove = (event: React.MouseEvent) => { | |
if (reference?.current) { | |
const { pageX, pageY } = event; | |
const { offsetX, offsetY } = getTotalOffset(reference.current); | |
const x = pageX - offsetX; | |
const y = pageY - offsetY; | |
setMousePointer({ | |
x, | |
y, | |
}); | |
} | |
}; | |
const styles = { | |
"--x": mousePointer.x, | |
"--y": mousePointer.y, | |
} as React.CSSProperties; | |
return [mouseMove, styles]; | |
} | |
export default useMouseMove; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is this?
This is a hook that is used for tracking mouse movements relative to an element - returning coordinates as CSS variables in a react css style object.
Example of use
Component.tsx:
styles.css: