r/reactjs•
swappea

[React - TS] Need help in resolving incompatible types for useRef and forwardRef.

Needs Help

So I am migrating our components to Typescript and we have one set of components regarding Button and Menu. Unfortunately I cannot share the code, but I have tried to recreate the given components on Playcode online.

Here is the link: https://playcode.io/1811917

Now I know forwardRef and mutableRef are not compatible, but not sure how I will handle this scenario.

Error: BugFinder: Type 'ForwardedRef<HTMLElement>' is not assignable to type 'MutableRefObject<HTMLElement>'.BugFinder:

Type '(instance: HTMLElement) => void' is not assignable to type 'MutableRefObject<HTMLElement>'.

​

Posted Mar 24, 2024, 9:20 AM UTC

11
No_Union816•

Try changing your InnerComponent anchorToRef type to:

React.Ref<HTMLElement>

You are passing MutableRefObject which is an object with property current.
However forwardRef function expects you to accept ForwardedRef type which is union of RefObject and RefCallback that you do not accept in your anchorToRef type.

3
swappeaOP•

Yes, thank you. You are right.

1
[deleted]•

[removed]

1