question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DragOverlay Not Working With Sortable Context

See original GitHub issue

Use Case Users need to be able to move squares around specific squares (in a certain order), so I thought that using SortableContext would be both be the simplest solution that would solve my problem. I’d also love to render a ‘default state’ of sorts when the users are moving the objects (ie a card with a number shows up)

Problem When using drag overlay, instead of staying where the original SortableItem was, it moves around alongside the item being moved. Do you know how I could fix this?

Here’s a video of the problem

https://user-images.githubusercontent.com/18711855/107376616-b8f7ca00-6aaf-11eb-9cb0-feab16c285e0.mp4

Package Information

{
    "@dnd-kit/core": "^1.0.0",
    "@dnd-kit/sortable": "^1.0.0",
}

Component In Question:

export const ScavengerHunt: React.FC<IScavengerHunt> = ({ questions }) => {
  const [activeId, setActiveId] = useState<null | string>(null);
  const [currentQuestions, setQuestions] = useState(
    questions as Array<ISHModule>
  );
  const sensors = useSensors(
    useSensor(TouchSensor),
    useSensor(MouseSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    const oldId = over ? over.id : "";
    setActiveId(null);
    if (active.id !== oldId) {
      setQuestions((oldQuestions) => {
        const oldIndex = oldQuestions.findIndex(
          (question) => question.id === active.id
        );
        const newIndex = oldQuestions.findIndex(
          (question) => question.id === oldId
        );

        return arrayMove(oldQuestions, oldIndex, newIndex);
      });
    }
  };

  const handleDragStart = (event: DragStartEvent) => {
    const { active } = event;
    setActiveId(active.id);
  };

  const normalizedQuestions = currentQuestions.map((question) => question.id);

  const rows = lodash.chunk(currentQuestions, 3);

  return (
    <DndContext
      sensors={sensors}
      onDragEnd={handleDragEnd}
      onDragStart={handleDragStart}
    >
      <SortableContext items={normalizedQuestions}>
        <Grid container spacing={4}>
          {rows.map((row, index) => {
            const direction = (index + 1) % 2 === 0 ? "row-reverse" : "row";

            return (
              <Grid
                container
                item
                direction={direction}
                key={index}
                spacing={4}
              >
                {row.map((question) => {
                  return (
                    <Grid item xs={4} key={question.id}>
                      <SortableItem id={question.id}>
                        <SHQuestion {...question} />
                      </SortableItem>
                    </Grid>
                  );
                })}
              </Grid>
            );
          })}
        </Grid>
      </SortableContext>
      {createPortal(
        <DragOverlay>{activeId && <p>{activeId}</p>}</DragOverlay>,
        document.body
      )}
    </DndContext>
  );
};

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
alimertcakarcommented, Jul 28, 2022

I thought DragOverlay was supposed to show in the place of the item being dragged too. However, I quickly figured out that this is not the intended case for this library as clauderic pointed out too.

You need to disable transform property of the Draggable component for the desired effect.

E.g:

const Draggable = ({...,hasDragOverlay,...}){
...
const style = {
    transform: hasDragOverlay ? "unset" : CSS.Translate.toString(transform),
  };
...
}
// set hasDragOverlay to true if you are gonna use DragOverlay
1reaction
claudericcommented, Feb 9, 2021

Hey @LuisOsta,

I’m not sure I understand the problem. Can you elaborate?

The <DragOverlay> component provides a way to render a draggable overlay that is removed from the normal document flow and is positioned relative to the viewport and follows the cursor. This seems to be working as expected in the video you posted above.

As for the sortable items, they move in response to the collision detection algorithm detecting which item the drag overlay is currently over, and their position updates depending on the sorting strategy, which also seems to be working as expected in the video you posted.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sortable - dnd-kit – Documentation
The SortableContext provides information via context that is consumed by the useSortable hook, which is covered in greater detail in the next section....
Read more >
@dnd-kit/sortable examples - CodeSandbox
Learn how to use @dnd-kit/sortable by viewing and forking @dnd-kit/sortable example apps on CodeSandbox.
Read more >
drag and drop library dnd-kit not working in my React example
I been working on a very basic example with help of the guide for sorting list with overlay but it doesn't work and...
Read more >
React Drag And Drop List With dnd Kit (React Drag ... - YouTube
Enjoying my videos? Sign up for FREE content here: https://www.thecoopercodes.com/In this video I go over how to create a sortable list with ...
Read more >
Let's build a DRAG & DROP list In React / @DND-kit - YouTube
Let's build a DRAG & DROP list In React / @DND-kit* Github repo - https://github.com/recraftrelic/react-dnd@DND-kit===========* DND kit Docs ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found