I create a drag and drop component using React hook, with the callback function when drag enters below. If I use the line dragItem.current.itemIndex, 1
instead of currentItemIndex, 1
it is not working. Can somebody tell me why? Thanks!!!
Call back here:
const handleDragEnter = function handleDragEnter(e, targetItem) {
if (dragItemNode.current !== e.target) {
const currentItemIndex = dragItem.current.itemIndex
setOrder((oldOrder) => {
let newOrder = JSON.parse(JSON.stringify(oldOrder));
newOrder.splice(
targetItem.itemIndex,
0,
newOrder.splice(
//currentItemIndex, 1 // working
dragItem.current.itemIndex, 1 // not working
)[0]
);
dragItem.current.itemIndex = targetItem.itemIndex
return newOrder;
});
}
};
Full code here:
function DragNDrop({
items,
order,
setOrder,
}) {
const [dragging, setDragging] = useState(false);
const dragItem = useRef();
const dragItemNode = useRef();
const handleDragStart = function handleDragStart(e, item) {
dragItemNode.current = e.target;
dragItemNode.current.addEventListener("dragend", handleDragEnd);
dragItem.current = item;
setTimeout(() => {
setDragging(true);
}, 0);
};
const handleDragEnter = function handleDragEnter(e, targetItem) {
if (dragItemNode.current !== e.target) {
const currentItemIndex = dragItem.current.itemIndex
setOrder((oldOrder) => {
let newOrder = JSON.parse(JSON.stringify(oldOrder));
newOrder.splice(
targetItem.itemIndex,
0,
newOrder.splice(
//currentItemIndex, 1 // working
dragItem.current.itemIndex, 1 // not working
)[0]
);
dragItem.current.itemIndex = targetItem.itemIndex
return newOrder;
});
}
};
const handleDragEnd = function handleDragEnd(e) {
dragItem.current = null;
dragItemNode.current.removeEventListener("dragend", handleDragEnd);
dragItemNode.current = null;
setDragging(false);
};
const getStyles = (item) => {
if (dragItem.current.item == item.item) {
return "dnd-item current";
}
return "dnd-item";
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
}}
className="drag-n-drop"
>
{order.map((item, itemIndex) => (
<div
draggable
key={item}
onDragStart={(e) => handleDragStart(e, {item, itemIndex})}
onDragEnter={
dragging
? (e) => {
handleDragEnter(e, {item, itemIndex});
}
: null
}
className={dragging ? getStyles({item, itemIndex}) : "dnd-item"}
>
{items[item]}
</div>
))}
</div>
);
}