How to use useRef with Typescript/Formik?

Viewed 3417

I am passing a ref property into my custom FieldInput that I use for Formik validation of my form. However, it gives a few Typescript errors. For instance, in my function:

    const handleSubmitForm = (
    values: FormValues,
    helpers: FormikHelpers<FormValues>,
  ) => {

    setShowFlatList(true);
    Keyboard.dismiss();
    helpers.resetForm();
    if (fieldRef && fieldRef.current){
          fieldRef.current.blur();}
    helpers.resetForm();
  };

I get an error on fieldRef.current that Object is possibly 'undefined'.. I thought adding the if condition would fix it but it didn't. Also, when I submit the form, I get a warning that

Warning: An unhandled error was caught from submitForm()
Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm 

Similarly, in my custom FieldInput component where I use ref={fieldRef}, I get an error that:

Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

How can I fix these?

Here's a codesandbox:

https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

1 Answers

If you look into current generic types of your forwardRef method, first parameter is unknown. Just change your signature method of input to

export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)

Typescript will automatically resolve correct type based on forwardRef method return type.

Related