8

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'.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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> 

Comments

0

This works in React-dnd (16.0.1), React (19.1.0) and Next (15.5.4)...

const [ collected, drag] = useDrag(() => ({ ... collect: (monitor) => ({ isDragging: monitor.isDragging(), }), })); return ( <div ref={drag} style={{ opacity: isDragging ? 0 : 1, }} > <p>Content</p> </div> ); ... 

...but there is a type warning:

TS2322: Type ConnectDragSource is not assignable to type Ref<HTMLDivElement> | undefined Type ConnectDragSource is not assignable to type (instance: HTMLDivElement | null) => void | (() => VoidOrUndefinedOnly) Type ReactElement<unknown, string | JSXElementConstructor<any>> | null is not assignable to type void | (() => VoidOrUndefinedOnly) Type null is not assignable to type void | (() => VoidOrUndefinedOnly) 

I read this as just being a conflict over null != void | (() => VoidOrUndefinedOnly.

For better or worse I wasn't worried about that, so I silenced the type warning:

ref={drag as unknown as Ref<HTMLDivElement>} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.