TanStackT
TanStack6mo ago
37 replies
popular-magenta

custom reusable form.Field component, trying to use Form Composition

Hello, I am reading the docs of Form Composition and I just saw the example of creating a form.Subscribe wrapper for a subscription button, so I guess that, for example, I could create a reusable component to be used for all my form.Field text inputs. This is my first attempt:
import type { ZodObject, ZodRawShape } from "zod";
import LabeledField from "@/components/form/labeled-field";
import { isFieldRequired, useFormContext } from "@/components/form/utils";
import { Input } from "@/components/ui/input";

interface FieldInputProps {
  id: string;
  fieldName: string;
  label: string;
  schema: ZodObject<ZodRawShape>;
}

export default function FieldInput({ id, fieldName, label, schema }: FieldInputProps) {
  const form = useFormContext();

  return (
    <form.Field
      name={fieldName}
      children={({ state, handleChange, handleBlur }) => (
        <LabeledField labelFor={id} label={label} required={isFieldRequired(fieldName, schema)}>
          <Input id={id} value={state.value ?? ""} onChange={(e) => handleChange(e.target.value)} onBlur={handleBlur} />
        </LabeledField>
      )}
    />
  );
}

However... The name prop shows Type 'string' is not assignable to type 'never'.ts(2322), and
state
is never too. Am I doing something wrong?
Was this page helpful?