Skip to content

useDragAndDrop

You can handle the user drag actions on a container element using this hook, and it can also handle the mobile touches.

Parameters

  1. the drag action handler function that takes the DragAction object as a parameter.
  2. and some drag options:
NameTypeDescription
refRefObjectthe container element reference (default is window).

Return Values

a ref object of the container element.

DragAction Object

NameTypeDescription
typeStringthe drag type which can be start, end, or moving.
clientXNumberthe x position.
clientYNumberthe y position.
initialXNumberthe initial x position.
initialYNumberthe initial y position.
targetElementthe current dragged element in the container.
eventEventthe MouseEvent or TouchEvent if you are using the touches property.

Example Usage

tsx
import { useDragAndDrop } from 'react-pre-hooks';

export default function Example() {
  const ref = useDragAndDrop(action => {
    const target = action.target as HTMLSpanElement;

    target.style.left = action.clientX + 'px';
    target.style.top = action.clientY + 'px';
  });

  return (
    <div ref={ref}>
      <span>Drag me!</span>
    </div>
  );
}
import { useDragAndDrop } from 'react-pre-hooks';

export default function Example() {
  const ref = useDragAndDrop(action => {
    const target = action.target as HTMLSpanElement;

    target.style.left = action.clientX + 'px';
    target.style.top = action.clientY + 'px';
  });

  return (
    <div ref={ref}>
      <span>Drag me!</span>
    </div>
  );
}

Released under the MIT License.