Skip to content

useDrag

Makes an element draggable and writes payload data to dataTransfer.

Makes an element draggable and writes payload data to dataTransfer.

Import

import { useDrag } from '@kamod-ch/hooks'

Live demo

Basic demo

Makes an element draggable and writes payload data to dataTransfer.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useDrag, useDrop } from '@kamod-ch/hooks'

export default function UseDragDemo() {
  const sourceRef = useRef<HTMLDivElement>(null)
  const targetRef = useRef<HTMLDivElement>(null)
  const [dropped, setDropped] = useState('nothing yet')
  useDrag({ label: 'Dragged card' }, sourceRef)
  useDrop(targetRef, { onDom: (content) => setDropped(content?.label ?? 'received data') })

  return (
    <div class="demo-grid">
      <div ref={sourceRef} class="demo-target-box">Drag me</div>
      <div ref={targetRef} class="demo-target-box">Drop here</div>
      <p><strong>Last drop:</strong> {dropped}</p>
    </div>
  )
}

API

TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
export interface Options {
    onDragStart?: (event: DragEvent) => void;
    onDragEnd?: (event: DragEvent) => void;
    dragImage?: {
        image: string | Element;
        offsetX?: number;
        offsetY?: number;
    };
}
declare const useDrag: <T>(data: T, target: BasicTarget, options?: Options) => void;
export default useDrag;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.