Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach a property to a functional component wrapped with React.forwardRef

I have a component wrapped with React.forwardRef and it so happens that it is a compound component as well.

I'm not sure how do I maintain

Form.Item  = FormItem;

while the Form component function being wrapped with forwardRef.

const Form = React.forwardRef((props, ref) => { return <form></form>});

Typescript gives me an error (rigthly) saying

Property 'Item' does not exist on type 'ForwardRefExoticComponent>'.ts(2339)

like image 501
HalfWebDev Avatar asked Oct 19 '25 02:10

HalfWebDev


1 Answers

Just to make it more clear of the solution, as it's on an external site (Credits to original author here, and thank you @Antoan Elenkov)

export interface Props = {
   ...yourPropsHere;
};

export interface CompoundedComponent extends React.ForwardRefExoticComponent<Props & React.RefAttributes<HTMLInputElement>> {
   yourStaticFunctionOrSomethingLikeThat: () => void;
}

const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => (
    <input ref={ref} {...props} />
)) as CompoundedComponent;

Component.yourStaticFunctionOrSomethingLikeThat = () => {};
like image 61
Petros Kyriakou Avatar answered Oct 21 '25 16:10

Petros Kyriakou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!