dnd-kit: Documentation code for Sortable with Typescript not working

I am playing around with the library in a project (which uses TypeScript).

The code in the Quick start section for a simple drag-and-drop works, but with this code, nothing moves and there is no interactivity.

I am going on a few hours without being able to find out what is wrong. I would be very happy to accept some pointers 😃

The code below contains two components that are to a large extent just taken stright out of the documentation for Sortable.

There are no errors in the console, and everything compiles.

import { DndContext, MouseSensor, useSensor, useSensors } from "@dnd-kit/core";
import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import React, { ReactNode, useState } from "react";

export const ExpSortable = () => {
  const [items, setItems] = useState(["1", "2", "3"]);
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 10
      }
    })
  );

  return (
    <DndContext sensors={sensors} onDragEnd={handleDragEnd}>
      <SortableContext items={items}>
        {items.map((id) => (
          <SortableItem key={id} id={id}>
            <p>hello from {id}</p>
          </SortableItem>
        ))}
      </SortableContext>
    </DndContext>
  );

  function handleDragEnd(event: any) {
    const { active, over } = event;
    console.log("drag end!");
    if (active.id !== over.id) {
      setItems((items) => {
        const oldIndex = items.indexOf(active.id);
        const newIndex = items.indexOf(over.id);
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  }
};

export function SortableItem(props: { children?: ReactNode; id: string }) {
  const { listeners, setNodeRef, transform, transition } = useSortable({
    id: props.id
  });

  const style = {
    padding: "5vmin",
    background: "orange",
    border: "2px solid",
    transform: CSS.Transform.toString(transform),
    transition
  } as React.CSSProperties;

  return (
    <div ref={setNodeRef} style={style} {...listeners}>
      {props.children}
    </div>
  );
}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 2
  • Comments: 22 (7 by maintainers)

Most upvoted comments

@rayshan

I pretty much just followed the quick start guide. The basic gist is to create two components, one that wraps useDroppable and another that wraps useDraggable. Then use the components with a unique id for each instance and wrap the whole thing in DndContext. I also have DragOverlay as a sibling to my container of draggables & droppables.

I can give you my example code, but I’ll have to do it later and it might just be faster to follow the quick start guide.

Thanks! npx yarn-deduplicate didn’t seem to work, but uninstalling all of the @dnd-kit packages and re-installing them did the trick.