Skip to content

Instantly share code, notes, and snippets.

@awebartisan
Last active November 2, 2020 19:35
Show Gist options
  • Save awebartisan/e443b7bb06cfdd051a1ef4a72a3b7679 to your computer and use it in GitHub Desktop.
Save awebartisan/e443b7bb06cfdd051a1ef4a72a3b7679 to your computer and use it in GitHub Desktop.
useDragDrop hook that handles DragStart, DragOver and Drop operations
import React from 'react';
const handleDragStart = (event: React.DragEvent) => {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData(
'text/plain',
event.currentTarget.getAttribute('data-index'),
);
};
const handleDragOver = (event: React.DragEvent) => {
event.preventDefault();
event.dataTransfer.effectAllowed = 'move';
};
const handleDrop = (event: React.DragEvent) => {
event.persist();
event.preventDefault();
const dragStartIndex = parseInt(event.dataTransfer.getData('text/plain'));
const dragEndIndex = parseInt(event.currentTarget.getAttribute('data-index'),
);
return {
dragStartIndex,
dragEndIndex,
};
};
export const useDragDrop = () => {
return {
handleDragStart,
handleDragOver,
handleDrop,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment