1 import type { DragEvent, ReactNode } from 'react';
2 import { useEffect, useMemo, useRef } from 'react';
3 import { createPortal } from 'react-dom';
5 interface DragMoveContentProps<T> {
11 interface UseDragMoveParams {
13 setDragging: (value: boolean) => void;
15 formatter?: (value: any) => string;
18 function useDragMove({ dragging, setDragging, format = 'text/plain', formatter = (str) => str }: UseDragMoveParams) {
19 const container = useRef<HTMLDivElement>();
20 const transferData = useRef<any>();
22 const handleDragStart = (event: DragEvent<HTMLTableRowElement>) => {
23 if (!container.current) {
24 container.current = document.createElement('div');
25 container.current.className = 'absolute';
27 document.body.appendChild(container.current);
28 event.dataTransfer.setDragImage(container.current, 0, 0);
29 event.dataTransfer.setData(format, formatter(transferData.current));
33 const handleDragEnd = () => {
34 if (container.current) {
35 document.body.removeChild(container.current);
41 const DragMoveContent = useMemo(
43 function Component<T>({ children, data, dragging }: DragMoveContentProps<T>) {
44 transferData.current = data;
48 transferData.current = undefined;
52 if (dragging && container.current) {
53 return createPortal(children, container.current);
60 return { dragging, handleDragEnd, handleDragStart, DragMoveContent };
63 export default useDragMove;