React with TypeScript: how to create ref prop

2.1k Views Asked by At

I am using Ionic with React (typescript) and I am creating my custom form builder. There I created my form that has to have a ref property, because I need a reference of it when I use it. My problem is that I don't know how to define a prop that is reference type for my custom form builder.

This is how I am using it:

const form = useRef<HTMLFormElement>(null);

return (
  <IonPage>
    <Header />
    <IonContent fullscreen>
      <Form
        ref={form}
        submit={() => onSubmit()}
        fields={ fields }
        render={() => (
          <React.Fragment>
            <IonCard>
              <IonCardHeader>
                <IonLabel>Valamilyen form</IonLabel>
              </IonCardHeader>
              <IonCardContent>
                <Field {...fields.name} />
              </IonCardContent>
            </IonCard>
          </React.Fragment>
        )}/>
    </IonContent>
    <Footer />
  </IonPage>
);

Here I got an error: Property 'ref' does not exist on type 'IntrinsicAttributes & IFormProps & IFormState & { children?: ReactNode; }'

My Form React.FC looks like this:

type formProps = IFormProps & IFormState;
    
export const Form: React.FC<formProps> = React.forwardRef<HTMLFormElement, formProps>( (props: formProps, porpsRef) => {
  return (
    <form onSubmit={handleSubmit} noValidate={true} ref={porpsRef} />
  );
)};

I need to add to my Form component a property named ref of the reference, but I don't know how.

Thanks

2

There are 2 best solutions below

2
On

I think there is small mistake. Can you please try this

type formProps = IFormProps & IFormState;

export const Form: React.FC<formProps> = 
React.forwardRef<formProps, HTMLFormElement>( (props: 
formProps, porpsRef) =>
{
   return (
       <form onSubmit={handleSubmit} noValidate={true} ref= 
      {porpsRef} />
    );
 )};
0
On

I just typed a very long answer to a similar question. In your case you seem to be making only one of those mistakes, which is declaring your Form as React.FC. The FC interface isn't aware of the ref forwarding that you've added with React.forwardRef so that's why you get an error when trying to pass a prop ref to it.

Delete this bit : React.FC<formProps> and you should be fine. You've already typed the generics on the React.forwardRef function, so typescript will know the return type and apply it to Form.

export const Form = React.forwardRef<HTMLFormElement, formProps>(...

If you wanted to explicitly declare the type, you can do that but it's a mouthful.

export const Form: React.ForwardRefExoticComponent<formProps & React.RefAttributes<HTMLFormElement>> = ...

(also you've forgotten to destructure handleSubmit from formProps)