fn

useDraggable

v0.0.14testeddemo

Make an element draggable by pointer, tracking its position with optional axis locking, a drag handle, container constraints, and lifecycle callbacks. SSR-safe and built on passive pointer listeners.

Examples

ts
const el = useTemplateRef<HTMLElement>('el');
const { x, y, style } = useDraggable(el, { initialValue: { x: 40, y: 40 } });
ts
// Lock to the horizontal axis and only drag from a handle.
const { position } = useDraggable(el, { axis: 'x', handle: handleEl });

Demo

Loading demo…

Signature

ts
export function useDraggable(
  target: MaybeComputedElementRef,
  options: UseDraggableOptions ={ ... }

Parameters

ParameterTypeDescription
targetMaybeComputedElementRefThe element to make draggable
options?UseDraggableOptionsOptions

Returns

UseDraggableReturnReactive x, y, position, isDragging, and a style string
PropertyTypeDescription
xRef<number>Current x position.
yRef<number>Current y position.
positionRef<Position>Current position as a { x, y } object.
isDraggingComputedRef<boolean>Whether a drag is currently in progress.
styleComputedRef<string>Ready-to-bind inline style string positioning the element.