3

Here I am trying to assign React dnd "drag" ref to existing ref but it is not happening, can any one please help me.

  const refs = useRef<(HTMLDivElement | null)[][]>([]);
const [{ isDragging }, drag] = useDrag(() => ({
    type: ItemType.item,
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging(),
    }),
  }));
  for (let curRow = 1; curRow <= props.row; curRow++) {
    for (let curCol = 1; curCol <= props.col; curCol++) {
      columns.push(
        <div
          onClickCapture={() => moseHandler(curRow, curCol)}


          ref={(el) => {      //----------------------------->for this ref I want to assign Drag ref
            refs.current[curRow] = refs.current[curRow] || [];
            refs.current[curRow][curCol] = el;
          }} 


          className="el1"
          id={`${curRow}${curCol}`}
          key={`${curRow}${curCol}${generateKey(curCol)}`}
        >
         {`${curRow}${curCol}`}
        </div>
      );
    }
  }```

2 Answers2

1

How do I combine several drag sources and drop targets in a single component? Both useDragand useDropreturn functions that may be chained against within a node's ref function. For example:

const [, drag] = useDrag(...args) const [, drop] = useDrop(...args)

return <div ref={(node) => drag(drop(node))}>

https://react-dnd.github.io/react-dnd/docs/faq

Betty
  • 9,109
  • 2
  • 34
  • 48
0

You can use react-merge-refs to assign react-dnd's drop ref and the the ref you created onto the same element.

Tyler Dane
  • 951
  • 1
  • 14
  • 25