October 21, 2024
Chicago 12, Melborne City, USA
javascript

Make dragged item ghost reverts to new position if dropped out of bounds


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:

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:

enter image description here

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



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video