I am trying to make my component accept a ref.
I have a component like so:
const MyComponent: RefForwardingComponent<HTMLDivElement, IMyComponentProps> = (props, ref) => {
return <div ref={ref}>Hoopla</div>
}
But when I try to pass a ref to is like so:
<MyComponent ref={myRef}></MyComponent>
... I get this error:
Property 'ref' does not exist on type 'IntrinsicAttributes & IMyComponentProps & { children?: ReactNode; }'.ts(2322)
What am I doing wrong?
RefForwardingComponent
is a render function, which receives props and ref parameters and returns a React node - it is no component:That is also the reason, why
RefForwardingComponent
is deprecated in favor ofForwardRefRenderFunction
, which is functionally equivalent, but has a different name to make the distinction clearer.You use
React.forwardRef
to turn the render function into an actual component that accepts refs:I think this is a bug in React's type definitions for
RefForwardingComponent
. You can work around this by adding theref?: React.RefObject<HTMLDivElement>
to your props. This will fix your compiler error.try this:
I believe this requirement is a bug, because it should be added to the props for you by
RefForwardingComponent
. Putting it in your own props means that TypeScript will expect theprops
argument inside your function to contain theref
prop and I don't think it does. This however is not a big problem.Custom function components can't have 'ref' as a prop. You will have to give it a different name. 'yourRef', for example will be inside the props object.
So to use the ref prop:
or you can descructure the props:
Your code is right but you are missing a small detail.
When you use
RefForwardingComponent
you need to export the component wrapped withforwardRef