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'.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With