TanStackT
TanStack4mo ago
16 replies
specific-silver

TypeScript: pass result of useForm as component props

Hi,

I am trying to pass my form created by
useForm
via props to a child component but I am not sure how to properly type it in the TypeScript.

Here is an example:

import { ReactNode } from "react";
import { useForm } from "@tanstack/react-form";

function Parent() {
  const form = useForm({
    defaultValues: {
      emailAddress: "",
    },
    onSubmit: async ({ value }) => {
      alert(value.emailAddress);
    },
  });

  return (
    // following line shows type error
    <Child form={form}>
      {(form) => (
        <form.Field
          name="emailAddress"
          children={(field) => (
            // render the form field
            <></>
          )}
        />
      )}
    </Child>
  );
}

function Child<TForm extends ReturnType<typeof useForm>>(props: {
  readonly form: TForm;
  readonly children: (form: TForm) => ReactNode;
}) {
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        props.form.handleSubmit();
      }}
    >
      {/* here goes some additional markup */}
      {props.children(props.form)}
      <props.form.Subscribe
        selector={(state) => [state.canSubmit, state.isSubmitting]}
        children={([canSubmit]) => (
          <Button variant="contained" type="submit" disabled={!canSubmit}>
            Submit
          </Button>
        )}
      />
    </form>
  );
}


Type error shown:

Type 'ReactFormExtendedApi<{ emailAddress: string; }, FormValidateOrFn<{ emailAddress: string; }> | undefined, FormValidateOrFn<{ emailAddress: string; }> | undefined, ... 6 more ..., unknown>' is not assignable to type 'ReactFormExtendedApi<unknown, FormValidateOrFn<unknown> | undefined, FormValidateOrFn<unknown> | undefined, FormAsyncValidateOrFn<unknown> | undefined, ... 5 more ..., unknown>'.
Was this page helpful?