apps/docs/extend/sensors.mdx
Sensors detect user input and translate it into drag and drop operations. They handle the initiation, movement, and completion of drag operations from different input sources.
The @dnd-kit/dom package provides a set of built-in sensors that can be used to detect user input in the browser:
Sensors can be configured both globally and per draggable element. The sensors option accepts either an array or a function that receives the default sensors.
Use the function form to configure or add sensors without replacing the defaults:
import {DragDropManager} from '@dnd-kit/dom';
import {PointerSensor, PointerActivationConstraints} from '@dnd-kit/dom';
const manager = new DragDropManager({
sensors: (defaults) => [
...defaults,
PointerSensor.configure({
activationConstraints: [
new PointerActivationConstraints.Distance({value: 5}),
],
}),
],
});
Pass an array to fully replace the default sensors:
import {DragDropManager} from '@dnd-kit/dom';
import {
PointerSensor,
PointerActivationConstraints,
KeyboardSensor
} from '@dnd-kit/dom';
const manager = new DragDropManager({
sensors: [
PointerSensor.configure({
activationConstraints: [
new PointerActivationConstraints.Distance({value: 5}),
new PointerActivationConstraints.Delay({
value: 200,
tolerance: {x: 10, y: 5},
}),
]
}),
KeyboardSensor,
]
});
Sensors can also be configured on individual draggable elements:
const draggable = new Draggable({
id: 'draggable-1',
element,
sensors: [KeyboardSensor],
}, manager);
You can create custom sensors by extending the Sensor class:
import {Sensor} from '@dnd-kit/abstract';
interface CustomSensorOptions {
delay?: number;
}
class CustomSensor extends Sensor {
constructor(manager, options?: CustomSensorOptions) {
super(manager, options);
}
public bind(source) {
// Register event listeners
const unbind = this.registerEffect(() => {
const target = source.handle ?? source.element;
if (!target) return;
const handleStart = (event) => {
if (this.disabled) return;
this.manager.actions.setDragSource(source.id);
this.manager.actions.start({
event,
coordinates: getCoordinates(event)
});
};
target.addEventListener('customstart', handleStart);
return () => {
target.removeEventListener('customstart', handleStart);
};
});
return unbind;
}
}
Construction
Binding
Operation
Cleanup
bind(source: Draggable): Bind sensor to draggable elementenable(): Enable the sensordisable(): Disable the sensorisDisabled(): Check if sensor is disableddestroy(): Clean up sensor resourcesconfigure(options): Create a configured sensor descriptorconst configuredSensor = CustomSensor.configure({
delay: 500
});
const manager = new DragDropManager({
sensors: [configuredSensor]
});