dnd-kit
dnd-kit copied to clipboard
docs: dnd-kit/react - add example of `onDragEnd` for sortable list in migration guide to v2 - source target identical isSortable
This probably should be mentioned in the migration documentation.
Originally posted by @allicanseenow in #1664
@clauderic I would open a PR for adding an example to the docs, but i cannot find the docs website in the repo so i'm blocked. Is private?
Raw Content
// TODO: check import
import { useSortable, isSortable } from '@dnd-kit/react/sortable';
import { arrayMove } from '@dnd-kit/sortable'; // TODO: is correct ??
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Buy X', },
{ id: 2, text: 'Go to Y' }
]);
return (
<DragDropProvider
onDragEnd={(data) => {
if (isSortable(data.operation.source)) {
const oldIndex = data.operation.source.sortable.initialIndex;
const newIndex = data.operation.source.sortable.index;
const newTodos = arrayMove(todos, oldIndex, newIndex);
setTodos(newTodos);
}}
>
<div className="flex flex-col gap-2">
{todos.map((todo, index) => (
<TodoListItem
key={todo.id}
todo={todo}
index={index}
/>
))}
</div>
</DragDropProvider>
);
}
function TodoListItem({ todo, index }: { todo: Todo; index: number }) {
const { ref: sortableRef } = useSortable({ id: todoId, index });
return (
<UiTodoListItem
elRef={sortableRef}
todo={todo}
/>
);
}
FYI, arrayMove is now in @dnd-kit/helpers:
https://github.com/clauderic/dnd-kit/blob/2c4b739adc892d04ccbdd23a54641078ada8bb7d/packages/helpers/src/move.ts#L12