Skip to content

Instantly share code, notes, and snippets.

@tfiechowski
Last active January 27, 2020 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfiechowski/7a2b2092597bdb853e11269727c7a38d to your computer and use it in GitHub Desktop.
Save tfiechowski/7a2b2092597bdb853e11269727c7a38d to your computer and use it in GitHub Desktop.
import React, { memo, useRef } from "react";
import { useDrag, useDrop } from "react-dnd";
const DragItem = memo(({ id, onMoveItem, children }) => {
const ref = useRef(null);
const [{ isDragging }, connectDrag] = useDrag({
item: { id, type: "IMG" },
collect: monitor => {
return {
isDragging: monitor.isDragging()
};
}
});
const [, connectDrop] = useDrop({
accept: "IMG",
hover(hoveredOverItem) {
if (hoveredOverItem.id !== id) {
onMoveItem(hoveredOverItem.id, id);
}
}
});
connectDrag(ref);
connectDrop(ref);
const opacity = isDragging ? 0.5 : 1;
const containerStyle = { opacity };
return React.Children.map(children, child =>
React.cloneElement(child, {
forwardedRef: ref,
style: containerStyle
})
);
});
export default DragItem;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment