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.
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.
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.