reactjsreact-beautiful-dnd

React-Beautiful-DND: Dragging items but they dont change order


I have the following:

<DragDropContext>
<Droppable droppableId="droppable">
{(provided) => (
<div className="droppable" {...provided.droppableProps} ref={provided.innerRef}>
{inputFields.map((inputField, index) => {
return (
<Draggable key={'item-'+index} draggableId={'item-'+index} index={index}>
{(provided) => (
<div className="itineraryflex" ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
Item-{index}
</div>)}
</Draggable>
)
})}
{provided.placeholder}
</div>)}
</Droppable>
</DragDropContext>

It allows me to drag n drop the div, but the order does not stick and reverts back to the original order.

Why does it not reorder when dragging and dropping?


Solution

  • You have to implement onDragEnd function to DragDropContext component in order for it to reorder.

    Also, create useState to change state after reordering.

    const [inputs,updateInputField] = React.useState(InputFields);
    
    const handleDragEnd= result => {
        const {destination,source} = result;
        //console.log(result);
        if (!result.destination) return;
        
        
            const newItems= Array.from(inputs);
            const [reOrdered] = newItems.splice(source.index, 1);
            newItems.splice(destination.index, 0, reOrdered);
            updateInputField(newItems)
        }
    <DragDropContext onDragEnd={handleonDrag}>
    ....
    {inputs.map((inputField, index) => {.....}