Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign two refs to same element

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>
      );
    }
  }```
like image 945
Lalith Aditya Avatar asked Dec 05 '25 02:12

Lalith Aditya


1 Answers

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

like image 118
Betty Avatar answered Dec 07 '25 17:12

Betty