TypeScript warning with useDraggable() and React 19: Argument of type 'RefObject<HTMLDivElement | null>' is not assignable to parameter of type 'RefObject<HTMLElement> (minimal reproducible example included)
Consider the following code that uses @neodrag/react v2.3.1 (and was originally adapted from neodrag's react demo)
const [position, setPosition] = useState({ x: 0, y: 0 });
const draggableRef = useRef<HTMLDivElement>(null);
useDraggable(draggableRef, {
position: position,
onDrag: ({ offsetX, offsetY }) => setPosition({ x: offsetX, y: offsetY }),
});
- With React v18 (minimal reproducible example at Stackblitz), the code works as expected and no warnings are triggered.
- With React v19.2.0 (minimal reproducible example at Stackblitz), the behavior seems to be still correct, but TypeScript reports the following warning:
Argument of type 'RefObject<HTMLDivElement | null>' is not assignable to parameter of type 'RefObject<HTMLElement>'.
Type 'HTMLDivElement | null' is not assignable to type 'HTMLElement'.
Type 'null' is not assignable to type 'HTMLElement'.(2345)
const draggableRef: RefObject<HTMLDivElement | null>
This occurs on the call to useDraggable(draggableRef, ...
From the React 19 Upgrade Guide: "useRef still has a convenience overload for useRef<T>(null) that automatically returns RefObject<T | null>".
Meanwhile, useDraggable()'s signature expects React.RefObject<RefType> (and not e.g. React.RefObject<RefType | null> or React.Ref<RefType>).
This mismatch seems to explain the warning.
Could you please share your thoughts on the best way forward here?
- Should
useDraggable()be updated to accept e.g.React.RefObject<RefType | null>orReact.Ref<RefType>? (react-draggable's changelog mentions that they implemented something similar here) - Or, is there a recommended workaround for consumers of the library (e.g. I tried something in the minimal reproducible example at Stackblitz but that's far from ideal IMHO)?
Any guidance on the intended approach would be greatly appreciated, and I'd be happy to help to the best of my ability test or contribute a fix if needed.
Thank you for developing neodrag and, in advance, for taking the time to consider this issue.