dnd-kit provides accessible drag and drop.
Code:
1import {2 DndContext,3 closestCenter,4 DragEndEvent,5 DragOverlay,6} from "@dnd-kit/core";7import {8 SortableContext,9 useSortable,10 verticalListSortingStrategy,11} from "@dnd-kit/sortable";12import { CSS } from "@dnd-kit/utilities";1314function SortableItem({ id, text }) {15 const {16 attributes,17 listeners,18 setNodeRef,19 transform,20 transition,21 isDragging,22 } = useSortable({ id });2324 const style = {25 transform: CSS.Transform.toString(transform),26 transition,27 opacity: isDragging ? 0.5 : 1,28 };2930 return (31 <div ref={setNodeRef} style={style} {...attributes} {...listeners}>32 {text}33 </div>34 );35}3637function SortableList({ items, onReorder }) {38 const [activeId, setActiveId] = useState<string | null>(null);3940 const handleDragStart = (event) => {41 setActiveId(event.active.id);42 };4344 const handleDragEnd = (event: DragEndEvent) => {45 const { active, over } = event;46 setActiveId(null);4748 if (active.id !== over?.id) {49 const oldIndex = items.findIndex(i => i.id === active.id);50 const newIndex = items.findIndex(i => i.id === over?.id);51 const newItems = arrayMove(items, oldIndex, newIndex);52 onReorder(newItems);53 }54 };5556 return (57 <DndContext58 collisionDetection={closestCenter}59 onDragStart={handleDragStart}60 onDragEnd={handleDragEnd}61 >62 <SortableContext items={items} strategy={verticalListSortingStrategy}>63 {items.map(item => (64 <SortableItem key={item.id} id={item.id} text={item.text} />65 ))}66 </SortableContext>67 <DragOverlay>68 {activeId ? (69 <div>{items.find(i => i.id === activeId)?.text}</div>70 ) : null}71 </DragOverlay>72 </DndContext>73 );74}
Benefits: