Created
January 5, 2019 14:41
-
-
Save michaelneu/ab6c35266d3c64393f53aee473e8634c to your computer and use it in GitHub Desktop.
TypeScript React hook for drag'n'drop on elements
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 { useState } from "react"; | |
export const useDragAndDrop = <T extends HTMLElement>() => { | |
const [isDragging, setIsDragging] = useState(false); | |
const [innerOffsetX, setInnerOffsetX] = useState(0); | |
const [innerOffsetY, setInnerOffsetY] = useState(0); | |
const start = (event: React.MouseEvent<T, MouseEvent>) => { | |
const element = event.target as T; | |
const { left, top } = element.getBoundingClientRect(); | |
const { clientX, clientY } = event; | |
setInnerOffsetX(left - clientX); | |
setInnerOffsetY(top - clientY); | |
setIsDragging(true); | |
}; | |
const drag = (event: React.MouseEvent<T, MouseEvent>) => { | |
if (isDragging) { | |
const x = event.clientX + innerOffsetX; | |
const y = event.clientY + innerOffsetY; | |
const element = event.target as T; | |
element.style.left = `${x}px`; | |
element.style.top = `${y}px`; | |
} | |
}; | |
const end = () => { | |
setIsDragging(false); | |
}; | |
return [ | |
start, | |
drag, | |
end, | |
]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment