Skip to content

Instantly share code, notes, and snippets.

@EmrysMyrddin
Last active July 30, 2020 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmrysMyrddin/bff858ec39007470ad4b885b243b7774 to your computer and use it in GitHub Desktop.
Save EmrysMyrddin/bff858ec39007470ad4b885b243b7774 to your computer and use it in GitHub Desktop.
const useDnD = ({ onStart, onMove, onComplete }) => {
const [draging, setDraging] = useState(false)
const handleDragStart = useCallback(() => {
setDraging(true)
// [Record starting point]
onStart ?? onStart()
}, [setDraging, onStart])
const handleDragMove = useCallback(() => {
// [Calc the current position]
onMove ?? onMove()
}, [onMove])
const handleDragComplete = useCallback(() => {
setDraging(false)
// [Resize the element]
onComplete ?? onComplete()
}, [setDraging, onComplete])
useEffect(() => {
if(draging) {
document.addEventListener('mousemove', handleDragMove)
document.addEventListener('mouseup', handleDragComplete)
}
return () => {
document.removeEventListener('mousemove', handleDragMove)
document.removeEventListener('mouseup', handleDragComplete)
}
}, [draging, handleDragMove, handleDragComplete])
return handleDragStart
}
const DnD = () => {
const onComplete = useCallback(() => {
// handle drag complete
}, [])
return <div onMouseDown={useDnD({ onComplete )}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment