I am using react with typescript. I have two components, one is a child and the other one is a parent. I am forwarding ref to my child component and in my child component I binding my export with forwardRef but I am getting an error on export line saying: Argument of type 'FC<ComponentType>' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, ComponentType>'
Here is my code:
import { forwardRef } from 'react';
import './Label.css';
type LabelType = {
name: string
ref: any
}
const Label: React.FC<LabelType> = ({name, ref}) => {
return <label className='label' ref={ref}>
</label>;
};
export default forwardRef(Label);
The documentation explains how forwardRef works: you must define the ref as the second parameter of the function component (instead of including it in the props, which is the first parameter). Then pass your function component as the first argument to forwardRef.
Here is a link to where the function signature for
forwardRefis declared in the current version of the@types/reactpacakge. You can inspect it to learn about how I derived the types in the following examples.
Here are two ways you can implement the instruction above to fix your current component:
Supply the appropriate generic type parameters to forwardRef (then you don't need to annotate the function component directly):
TS Playground
import {default as React, forwardRef} from 'react';
import './Label.css';
export type LabelProps = {
name: string;
};
export const Label = forwardRef<HTMLLabelElement, LabelProps>(({name}, ref) => {
return (<label className='label' ref={ref}>{name}</label>);
});
export default Label;
Or, annotate the function component directly:
TS Playground
import {default as React, forwardRef} from 'react';
import './Label.css';
export type LabelProps = {
name: string;
};
const Label = forwardRef((
{name}: LabelProps,
ref: React.ForwardedRef<HTMLLabelElement>,
): React.ReactElement => {
return (<label className='label' ref={ref}>{name}</label>);
});
export default Label;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With