I have a list of items, I implemented Drag and Drop, when I move the item to a new location, it stays there, but when I move the Item to a new location and got out of bound with the dragged ghost item and end the drop there, the ghost returns to the initial position. How do I handle that?
Initial list:
Dragged item to position 3 (index 2) and then out of bounds, Ghost will return to initial position, but I save the changed position as the new list:
I am using react and this is how I handle my drag and drop:
const handleDragStart = ( e, index ) => {
const draggedHotelKey = Object.keys( hotelList )[index];
const draggedHotel = hotelList[draggedHotelKey];
setDraggedItem( {
hotel : draggedHotel,
startIndex : index,
} );
e.dataTransfer.effectAllowed = "move";
};
const handleDragOver = ( e, index ) => {
e.preventDefault();
if ( index === draggedItem.startIndex ) return;
const hotelKeys = Object.keys( hotelList );
const [ removedHotelKey ] = hotelKeys.splice( draggedItem.startIndex, 1 );
hotelKeys.splice( index, 0, removedHotelKey );
const updatedHotelList = hotelKeys.reduce( ( acc, key ) => {
acc[key] = hotelList[key];
return acc;
}, {} );
setHotelList( updatedHotelList );
setDraggedItem( ( prev ) => ( {
...prev,
startIndex : index,
} ) );
};
const handleDrop = async ( e ) => {
e.preventDefault();
try {
await dispatch( updateHotelList( selectedEventId, hotelList ) );
} catch ( error ) {
console.error( "Failed to update hotel list:", error );
setHotelList( initialHotelList );
}
};
I need some advice how to redirect the ghost or prevent the ghost from appearing at all