dnd-kit icon indicating copy to clipboard operation
dnd-kit copied to clipboard

How to get state of my array of sortable items after reorder ?

Open SpinBoxx opened this issue 9 months ago • 3 comments

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>
	);
}

SpinBoxx avatar Mar 29 '25 22:03 SpinBoxx

store your items in a useState hook, and set them in onDragEnd

aa087159 avatar Apr 02 '25 08:04 aa087159

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.

sazid avatar Jun 24 '25 19:06 sazid

Created a PR with the relevant example added to the doc #1749

sazid avatar Jun 24 '25 19:06 sazid