Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useDrag Ref type error with NextJS and react-dnd

Using react-dnd 16 with Next.js 14 and TypeScript, the refs within the return array of the useDrag and useDrop hooks are not assignable to LegacyRef. Other plataforms as Vite.Js gets the type fine.

Same code works in both, but nextjs gets type error.

const [{ isDragging }, dragRef] = useDrag(() => ({
    ...
  }));

<div ref={dragRef}>
    ....
</div>

Even with cast it can't be solved. How can I solve this type error?

Error: Type 'ConnectDragSource' is not assignable to type 'LegacyRef | undefined'.

like image 206
Luiz Henrique Avatar asked Jun 25 '26 00:06

Luiz Henrique


2 Answers

It seems that useDrag gives us a function that returns a React Element. This worked for me:

const [{ isDragging }, drag] = useDrag(...);

{ drag(
  <div>
      ....
  </div>
)}

Or if you want your entire component to be draggable, just

return drag(
  <div>...</div>
)

Use the same approach for const [{ isDragging }, drop] = useDrop(...)

It's worth noting that this is not a documented change to the API and I'm not sure if there are any implications of this approach, but so far I've not had any issues.

like image 60
JoGoFo Avatar answered Jun 26 '26 16:06

JoGoFo


Just make sure the drag/drop ref isn't the direct argument to the ref. Instead, pass a callback to the ref prop and call the drag/drop ref with the param of the ref callback.

const [{ isDragging }, dragRef] = useDrag(() => ({
    ...
  }));

<div 
  ref={el => {
    dragRef(el)
  }}
>
    ....
</div>
like image 43
rantao Avatar answered Jun 26 '26 16:06

rantao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!