Drag and Drop List
In this exercise, you are tasked with creating a simple Drag and Drop List component that allows users to reorder a list of items by dragging and dropping them. The Drag and Drop List should have the following features:
Display the list of items
Allow users to drag and drop items to reorder the list
useState
hook to manage the list stateSolution Walkthrough for Drag and Drop List
Spoiler Alert!
Don't read this unless you've already solved the problem.
items
and draggingItem
. items
represents the current order of the list items, while draggingItem
tracks the index of the item being dragged. We use the useState
hook to manage both of these state variables:const [items, setItems] = useState(initialItems);
const [draggingItem, setDraggingItem] = useState(null);
We'll need to handle three drag-and-drop events to enable list reordering:
onDragStart
: Triggered when the user starts dragging an item. We define the handleDragStart
function that takes the index of the dragged item and updates the draggingItem
state:function handleDragOver(index) {
if (draggingItem === null) return;
if (draggingItem === index) return;
const newItems = [...items];
const draggingItemValue = newItems[draggingItem];
newItems.splice(draggingItem, 1);
newItems.splice(index, 0, draggingItemValue);
setDraggingItem(index);
setItems(newItems);
}
onDragEnd
: Triggered when the user drops the dragged item. We define the handleDragEnd
function that resets the draggingItem
state to null
:function handleDragEnd() {
setDraggingItem(null);
}
draggable
attribute and attach the appropriate event handlers for the drag events:<ul>
{items.map((item, index) => (
<li
key={index}
draggable
onDragStart={() => handleDragStart(index)}
onDragOver={() => handleDragOver(index)}
onDragEnd={handleDragEnd}
>
{item}
</li>
))}
</ul>
DragDropList
component combines state management, event handling, and rendering to create a user-friendly drag-and-drop experience for reordering list items.