Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent scroll into nothing while draging

I use dnd-kit for react in a tanstack-table surrounded by a div which has scrollbars.

The Problem is, as shown in the gif below, i can scroll into nothing. I want to prevent that.

It should only scroll to the end of the table, both on x and y axis.

Unfortunately i can not use DndContext modifiers to restrict dragging to y axis since i also have to use the same DnDContext for the dragable table heasers (those can be rearranged).

I tried it with CSS (i use tailwind) but neither overscroll-behavior nor scroll-snap-stop worked, and i ran out of ideas.

enter image description here

Here is a stackblit example of the Problem, thou this is just for vertical. Simply giving overflow: visible to the parent element gives you the opportunity to scroll endlessly into nothing.

like image 505
Andresch Serj Avatar asked Nov 30 '25 10:11

Andresch Serj


1 Answers

You can try using a "useRef" hook combined with "handleDragMove" event handler for "DndContext" to control the element being scrolled outside of the container.

const containerRef = useRef<HTMLDivElement>(null);

function handleDragMove(event: any) {
  const { active } = event;
  const container = containerRef.current;

  if (!container || !active) return;

  const containerRect = container.getBoundingClientRect();
  const draggedItem = document.querySelector(`[data-id="${active.id}"]`) as HTMLElement;

  if (!draggedItem) return;

  const itemRect = draggedItem.getBoundingClientRect();

  if (
    itemRect.left < containerRect.left ||
    itemRect.right > containerRect.right ||
    itemRect.top < containerRect.top ||
    itemRect.bottom > containerRect.bottom
  ) {
    draggedItem.style.transform = `translate(0px, 0px)`;
  }
}

Additionally add position: relative; overflow: hidden; for .dnd-container div this ensures the element doesn't overflow outside of the container.

Modified stackblitz link

like image 133
Viira Avatar answered Dec 02 '25 23:12

Viira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!