apps/docs/extend/modifiers.mdx
Modifiers transform the movement of draggable elements during drag operations. They can restrict movement to axes or boundaries, adjust positioning, or implement any custom movement logic.
Available in @dnd-kit/abstract/modifiers, these modifiers are environment-agnostic:
Example using axis restriction:
import {RestrictToVerticalAxis} from '@dnd-kit/abstract/modifiers';
// Only allow vertical movement
const manager = new DragDropManager({
modifiers: [RestrictToVerticalAxis],
});
Example combining modifiers:
import {
Snap,
RestrictToHorizontalAxis
} from '@dnd-kit/abstract/modifiers';
// Horizontal movement that snaps to a grid
const manager = new DragDropManager({
modifiers: [
RestrictToHorizontalAxis,
Snap.configure({
size: {
x: 20, // Snap every 20px horizontally
y: 0 // No vertical snapping (already restricted)
}
})
],
});
Environment-specific modifiers for the DOM, available in @dnd-kit/dom/modifiers:
Modifiers can be applied globally or per draggable element. The modifiers option accepts either an array or a function that receives the default modifiers.
Use the function form to add modifiers without replacing the defaults:
import {DragDropManager} from '@dnd-kit/dom';
import {RestrictToWindow} from '@dnd-kit/dom/modifiers';
const manager = new DragDropManager({
modifiers: (defaults) => [...defaults, RestrictToWindow],
});
Pass an array to fully replace the default modifiers:
import {DragDropManager} from '@dnd-kit/dom';
import {RestrictToWindow} from '@dnd-kit/dom/modifiers';
const manager = new DragDropManager({
modifiers: [RestrictToWindow],
});
Modifiers can also be configured on individual draggable elements:
import {RestrictToElement} from '@dnd-kit/dom/modifiers';
const draggable = new Draggable({
id: 'draggable-1',
element,
modifiers: [
RestrictToElement.configure({
element: containerElement
})
],
}, manager);
Create custom modifiers by extending the Modifier class:
import {Modifier} from '@dnd-kit/abstract';
import type {Coordinates} from '@dnd-kit/geometry';
interface GridOptions {
gridSize: number;
}
class SnapToGrid extends Modifier {
constructor(manager, options?: GridOptions) {
super(manager, options);
}
public apply(operation): Coordinates {
if (this.disabled) return operation.transform;
const {gridSize = 20} = this.options ?? {};
const {transform} = operation;
return {
x: Math.round(transform.x / gridSize) * gridSize,
y: Math.round(transform.y / gridSize) * gridSize,
};
}
}
Construction
Application
apply() called during dragCleanup
apply(operation): Transform drag coordinatesenable(): Enable the modifierdisable(): Disable the modifierisDisabled(): Check if modifier is disableddestroy(): Clean up resourcesconfigure(options): Create configured modifierconst snapToGrid = SnapToGrid.configure({
gridSize: 10
});
const manager = new DragDropManager({
modifiers: [snapToGrid]
});