Skip to content

Instantly share code, notes, and snippets.

@Grsmto
Last active December 14, 2021 17:58
Show Gist options
  • Save Grsmto/26682fb458f03b788a1da4d29ff95dee to your computer and use it in GitHub Desktop.
Save Grsmto/26682fb458f03b788a1da4d29ff95dee to your computer and use it in GitHub Desktop.
React Hook to define if a mouse event is a drag or not
import React from "react"
export default function useIsDragged(ref, offset = 5) {
const isDragged = React.useRef(false)
const isDown = React.useRef(false)
const distance = React.useRef(0)
const mousePos = React.useRef({
x: 0,
y: 0,
})
React.useEffect(() => {
const el = ref.current
const handleMouseDown = event => {
isDown.current = true
isDragged.current = false
mousePos.current = {
x: event.clientX,
y: event.clientY,
}
}
const handleMouseMove = event => {
if (isDown.current) {
distance.current += Math.sqrt(
Math.pow(mousePos.current.y - event.clientY, 2) +
Math.pow(mousePos.current.x - event.clientX, 2)
)
mousePos.current = {
x: event.clientX,
y: event.clientY,
}
isDragged.current = distance.current > offset
}
}
const handleMouseUp = () => {
isDragged.current = false
isDown.current = false
distance.current = 0
mousePos.current = {
x: 0,
y: 0,
}
}
el.addEventListener("mousedown", handleMouseDown)
el.addEventListener("mousemove", handleMouseMove)
el.addEventListener("mouseup", handleMouseUp)
return () => {
el.removeEventListener("mousedown", handleMouseDown)
el.removeEventListener("mousemove", handleMouseMove)
el.removeEventListener("mouseup", handleMouseUp)
}
}, [ref, offset])
return isDragged
}
// usage
// const isDraggedRef = useIsDragged(domElementRef)
// if (isDraggedRef.current) { console.log('domElementRef is being dragged!) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment