Skip to content

Instantly share code, notes, and snippets.

@michaelneu
Created January 5, 2019 14:41
Show Gist options
  • Save michaelneu/ab6c35266d3c64393f53aee473e8634c to your computer and use it in GitHub Desktop.
Save michaelneu/ab6c35266d3c64393f53aee473e8634c to your computer and use it in GitHub Desktop.
TypeScript React hook for drag'n'drop on elements
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