dnd-kit
dnd-kit copied to clipboard
How to get state of my array of sortable items after reorder ?
Hello, I'm using the new useSortable hook from this library, and I want to retrieve my sortable items array. How can I proceed? I want to get my new state after the reorder. I read the doc, but I didn't find a way to do this. :/
const voteRoomPage = () => {
const items = ["Item 1", "Item 2", "Item 3", "Item 4"];
return (
<div className="space-y-24 pt-14">
<DragDropProvider>
<ul className="list">
{items.map((id, index) => (
<Sortable key={id} id={id} index={index} />
))}
</ul>
</DragDropProvider>
</div>
);
};
function Sortable({ id, index }: { id: string; index: number }) {
const { ref, sortable } = useSortable({ id, index });
return (
<li ref={ref} className="item">
Item {id}
</li>
);
}
store your items in a useState hook, and set them in onDragEnd
Found a solution to this. You need to first install the helpers package: npm i @dnd-kit/helpers.
And then, use it:
import { useState, useEffect } from 'react';
import { DragDropProvider } from '@dnd-kit/react';
import { move } from '@dnd-kit/helpers';
function SortableDemo() {
const [items, setItems] = useState([1, 2, 3, 4]);
useEffect(() => {
console.log(items);
}, [items]);
return (
<DragDropProvider onDragEnd={(event) => setItems(move(items, event))}>
<ul>
{items.map((id, index) => (
<Sortable key={id} id={id} index={index} />
))}
</ul>
</DragDropProvider>
);
}
This should ideally be included in the docs for useSortable as I've been looking for this as well.
Created a PR with the relevant example added to the doc #1749