Created
February 23, 2023 21:29
-
-
Save ValentaTomas/b0d198f9d4551a418511b56d6765e668 to your computer and use it in GitHub Desktop.
Helper hook for creating divs attached to mouse cursor
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 { useEffect, useState } from 'react' | |
export type UpdateIndicator = (x: number, y: number) => void | |
export function useMouseIndicator(indicatorFactory?: () => { el: HTMLElement; update: UpdateIndicator; }) { | |
const [isActive, setIsActive] = useState(false) | |
useEffect(function attach() { | |
if (!isActive) return | |
if (!indicatorFactory) return | |
const { el, update } = indicatorFactory() | |
const handleWindowMouseMove = (event: MouseEvent) => { | |
const x = event.clientX | |
const y = event.clientY | |
update(x, y) | |
} | |
window.addEventListener('mousemove', handleWindowMouseMove) | |
document.body.appendChild(el) | |
return () => { | |
window.removeEventListener('mousemove', handleWindowMouseMove) | |
document.body.removeChild(el) | |
} | |
}, [ | |
isActive, | |
indicatorFactory, | |
]) | |
return setIsActive | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment