Reputation: 3
I'm working with a drag and drop interaction in React.js. I'm reordering an array of 'rows' using the splice function that's called when the drag is finished using an onDragEnd function below:
onDragEnd = (result) => {
const { destination, source, draggableId, type } = result;
if (!destination) {
return;
}
if (
destination.draggableId === source.droppableId &&
destination.index === source.index
) {
return;
}
if (type === "row") {
const newRowOrder = Array.from(**this.state.currentRows**);
newRowOrder.splice(source.index, 1);
newRowOrder.splice(destination.index, 0, **draggableId**);
const newState = {
...this.state,
currentRows: newRowOrder,
};
this.setState(newState);
}
};
Before the onDragEnd function is called the currentRow state looks like this: currentRow state before onDragEnd
When the function is called, the splice function works (I think) but it doesn't move the whole object in the array, just the ID. The draggableId used in the splice function is the ID of the object that needs to be moved.
After the onDragEnd function is called the currentRow state looks like this: currentRow state after onDragEnd
Can the whole object be moved to a new index?
Upvotes: 0
Views: 420
Reputation: 326
I think you are just inserting the draggableId newRowOrder.splice(destination.index, 0, **draggableId**);
you could find the entire object with the Array.find
function and insert the whole object
onDragEnd = (result) => {
const { destination, source, draggableId, type } = result;
if (!destination) {
return;
}
if (
destination.draggableId === source.droppableId &&
destination.index === source.index
) {
return;
}
if (type === "row") {
const draggableRow = this.state.currentRows.find(row => row.id === draggableId);
const newRowOrder = Array.from(this.state.currentRows);
newRowOrder.splice(source.index, 1);
newRowOrder.splice(destination.index, 0, draggableRow);
const newState = {
...this.state,
currentRows: newRowOrder,
};
this.setState(newState);
}
}
Upvotes: 1