This library will help you to drag and drop elements on the web. With a very simple use it is perfect for drag and drop in simple or even complex scenarios.
npm install --save react-use-drag-and-drop
or
yarn add react-use-drag-and-drop
You need provide the drag and drop context
import { DragAndDropProvider } from 'react-use-drag-and-drop';
<DragAndDropProvider>
...
</DragAndDropProvider>
Now in your component you can use the hooks, first create your draggable component
import { useDrag } from 'react-use-drag-and-drop';
const MyComponentDraggable = () => {
const htmlRef = useRef(null);
//...
const { isDragging, preview } = useDrag({
id,
canDrag: true,
data: { counter },
element: elementToDragRef,
end: (props) => console.log('end', props),
start: (props) => console.log('start', props),
}, [counter, id]);
//...
return <button ref={htmlRef}>Drag button</button>
}
Now you ca create your droppable component
import { useDrop } from 'react-use-drag-and-drop';
const MyComponentDroppable = () => {
const htmlRef = useRef(null);
//...
const [{ isDraggingOver, isDraggingOverCurrent }] = useDrop({
id,
element: elementToDropRef,
drop: (data, monitor) => console.log('drop', data, monitor),
hover: (data, monitor) => console.log('hover', data, monitor),
leave: (data, monitor) => console.log('leave', data, monitor),
}, [id]);
//...
return <div ref={htmlRef}>Drop area div</div>
}
-
Clone this repository
-
Prefer to use yarn for dependency installation
-
Install the dependencies
yarn install
-
Run the example in local host
yarn dev
-
Change
package.json
version -
Build the package
yarn build
-
Publish the new version
npm publish