@dnd-kit not allowing to prevent dragging items

5k Views Asked by At

I'm using this npm package: @dnd-kit https://github.com/clauderic/dnd-kit to be able to drag drop elements up and down in a vertical list. Dragging elements works perfect for me. My problem is that based on some condition I need to block the dragging of the elements at all.

To reproduce the issue you can follow these steps:

$ git clone https://github.com/clauderic/dnd-kit
$ cd dnd-kit
$ git checkout master # currently: d5c4732d7262c773db338850e9b2bb386c938ddf
$ yarn
$ yarn start:storybook

On file: /stories/2 - Presets/Sortable/1-Vertical.story.tsx, just add the highlighted text on the screenshot below...

enter image description here

Here is the added text so you can copy paste:

export const LockedBothAxis = () => (
  <Sortable
    {...props}
    modifiers={[restrictToHorizontalAxis, restrictToVerticalAxis, restrictToWindowEdges]}
  />
);

where you can see my intention is to block the dragging on both axis: horizontal and vertical. Whenever the block condition is true I tried by using those 2 modifiers above: { restrictToHorizontalAxis, restrictToVerticalAxis } (which doesn't totally work).

Now go to: http://localhost:6006/?path=/story/presets-sortable-vertical--locked-both-axis and try to drag the items.

If you try a short distance dragging then you will notice the dragging doesn't work (so far so good).

My problem is: If you try a long distance dragging (all the way up or down) then you will notice that you can actually drag the items.

What I need: When the user long presses an item, the item gets highlighted but when he tries a short or a long distance dragging, the item doesn't get dragged.

Below you have a demostration of my issue, where I try first a short distance dragging up and down and the item doesn't get dragged (so far so good). But later I try a long distance dragging down and the item gets dragged (my issue)...

enter image description here

Any idea on how to block the dragging at all even if the user does a long distance dragging?

1

There are 1 best solutions below

0
On

Try to add disabled: true to useSortable or useDraggable

const [disableDnD, setDisableDnD] = useState(true);


const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: disableDnD });

Here are props: https://docs.dndkit.com/api-documentation/draggable/usedraggable#arguments