use-drags
TypeScript icon, indicating that this package has built-in type declarations

2.2.0 • Public • Published

Ci Status Npm version React version

use-drags

Handle drag events without overhead by only 1 callback. React hook for manage drag and drop lifecycle without extra business or view logic. Useful as base for custom UI components with draggable elements.

Demo

Package includes its TypeScript Definitions

Install

npm install use-drags

Usage

import React, { useRef, useState } = 'react';
import useDrags from 'use-drags';

function DraggableBlock() {
  const ref = useRef(null);
  const [position, setPosition] = useState(null);

  useDrags(ref, ({
    el,
    first,
    last,
    deltaX,
    deltaY,
    offsetX,
    offsetY,
    clientX,
    clientY,
  }) => {
    if (first) {
      el.style.opacity = 0.5;
    }

    if (last) {
      el.style.opacity = null;
      el.style.transform = null;
      setPosition(null);

      return;
    }

    setPosition({ clientX, clientY });

    el.style.transform = `translate3d(${offsetX}px, ${offsetY}px, 0)`;
  });

  return (
    <div ref={ref}>
      <span>Drag me!</span>
      {position !== null &&
        <span>X: {position.clientX }, Y: {position.clientY}</span>
      }
    </div>
  );
}

Development

npm run lint # linting
npm run test # testing

Active maintenance with care and ❤️.

Feel free to send a PR.

Package Sidebar

Install

npm i use-drags

Weekly Downloads

0

Version

2.2.0

License

MIT

Unpacked Size

41.1 kB

Total Files

10

Last publish

Collaborators

  • zamarawka