Skip to content

Instantly share code, notes, and snippets.

@robbdimitrov
Last active April 10, 2022 11:03
Show Gist options
  • Save robbdimitrov/1b20b83da195f96c069b6557b534cd05 to your computer and use it in GitHub Desktop.
Save robbdimitrov/1b20b83da195f96c069b6557b534cd05 to your computer and use it in GitHub Desktop.
Drag and drop in React
const handleDragStart = (e) => {
e.preventDefault();
if (e.target.className.includes('draggable')) {
setSelected(e.target);
}
};
const handleDragEnd = (e) => {
e.preventDefault();
let target = e.target;
if (e.type === 'touchend') {
const touch = e.changedTouches[0];
target = document.elementFromPoint(touch.clientX, touch.clientY);
}
if (selected && target.className.includes('draggable')) {
const start = selected.dataset['index'];
const end = target.dataset['index'];
setItems(reordered(items, start, end));
}
setSelected(null);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment