T
TanStack•13mo ago
xenophobic-harlequin

How do I use the fields in a form, in child components?

How do I get what fields I have in the parent component so I can pass them down to the child component? The fields in the form can differ depending on what the user does
No description
9 Replies
xenophobic-harlequin
xenophobic-harlequinOP•13mo ago
Ok I can pass the Field component down to the child. Is this the way to do it or is there a more beautiful way? 🙂
No description
conscious-sapphire
conscious-sapphire•13mo ago
FieldComponent is indeed your type. If you want to make it look nicer you can define in a type your form shape
export type FormData = {
comment1: string
comment2: string
...
}
export type FormData = {
comment1: string
comment2: string
...
}
And then use
FieldComponent<FormData>
FieldComponent<FormData>
flat-fuchsia
flat-fuchsia•13mo ago
And then how do you use it?
<StopsModelSplit
Field={} <-- what to pass here?
/>
<StopsModelSplit
Field={} <-- what to pass here?
/>
conscious-sapphire
conscious-sapphire•13mo ago
With that level of abstraction you should be able to pass form.Field
flat-fuchsia
flat-fuchsia•13mo ago
✅ Works - thank you 🙂 If you're using a Validation Adapter you need to add the Type as the 2nd argument to FieldComponent like so: Field: FieldComponent<FormData, ZodValidator> Here's a working example: https://stackblitz.com/edit/tanstack-form-vawcwu?file=src%2Findex.tsx
Pascal Küsgen
StackBlitz
Form Zod Example (forked) - StackBlitz
Run official live example code for Form Zod, created by Tanstack on StackBlitz
conscious-sapphire
conscious-sapphire•13mo ago
Yes, correct 🙂
flat-fuchsia
flat-fuchsia•13mo ago
I'm now also passing in the form to be able to access form.useStore and form.setFieldValue. To do this I'm passing:
function MyFormPart({
form,
Field,
}: {
form: FormApi<FormSchema, ZodValidator> & ReactFormApi<FormSchema, ZodValidator>;
Field: FieldComponent<FormSchema, ZodValidator>;
}) {
// …
}
function MyFormPart({
form,
Field,
}: {
form: FormApi<FormSchema, ZodValidator> & ReactFormApi<FormSchema, ZodValidator>;
Field: FieldComponent<FormSchema, ZodValidator>;
}) {
// …
}
conscious-sapphire
conscious-sapphire•13mo ago
If you're passing the entire form instance you probably don't need Field anymore
flat-fuchsia
flat-fuchsia•13mo ago
right… by keeping both the "MyFormPart" functions implementations stay similar inside (I have 3 of them). Any other way to only pass the values and handle updates? Let's say if someone inputs the "firstName" in the MyFormPart I make a request against my Backend and return the correct spelling to that name, then I'll set the value of the firstName field to whatever got returned from the Backend.

Did you find this page helpful?