Created
November 13, 2022 12:09
-
-
Save ljosberinn/1ffaca0997199f390681a6f0698e570a to your computer and use it in GitHub Desktop.
maybeUseHoverEffect
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
export function useHoverEffect({ ref }: { ref: MutableRefObject<HTMLElement | null >}) { | |
const mousePosition = useMousePosition() | |
const { x, y } = calculateOffset(ref, mousePosition) | |
return function Effect() { | |
return ( | |
<div style={{ | |
["--x" as any]: `${x}px`, | |
["--y" as any]: `${y}px`, | |
}} | |
className="absolute inset-0 -z-10 translate-x-[var(--x)] translate-y-[var(--y)]" | |
/> | |
) | |
} | |
} | |
function calculateOffset(ref: MutableRefObject<HTMLElement | null>, mousePosition: ReturnType<typeof useMousePosition>) { | |
if (!ref.current || !mousePosition.x || !mousePosition.y) { | |
return { x: 0, y : 0 } | |
} | |
const { left, top, width, height } = ref.current.getBoundingClientRect() | |
return { | |
x: mousePosition.x - left - width / 2, | |
y: mousePosition.y - top - height / 2, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment