Skip to content

Instantly share code, notes, and snippets.

@ljosberinn
Created November 13, 2022 12:09
Show Gist options
  • Save ljosberinn/1ffaca0997199f390681a6f0698e570a to your computer and use it in GitHub Desktop.
Save ljosberinn/1ffaca0997199f390681a6f0698e570a to your computer and use it in GitHub Desktop.
maybeUseHoverEffect
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