RefForwardingComponent
is a render function, which receives props and ref parameters and returns a React node - it is no component:
The second ref argument only exists when you define a component with React.forwardRef call. Regular function or class components don’t receive the ref argument, and ref is not available in props either. (docs)
That is also the reason, why RefForwardingComponent
is deprecated in favor of ForwardRefRenderFunction
, 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:
import React, { ForwardRefRenderFunction } from 'react'
type IMyComponentProps = { a: string }
const MyComponentRenderFn: ForwardRefRenderFunction<HTMLDivElement, IMyComponentProps> =
(props, ref) => <div ref={ref}>Hoopla</div>
const MyComponent = React.forwardRef(MyComponentRenderFn);
const myRef = React.createRef<HTMLDivElement>();
<MyComponent a="foo" ref={myRef} />
forwardRef
. A missingforwardRef
will eventually cause a runtime error:Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
. So OP does need forwardRef, but he hasn't made it that far yet. – Diazonium