T
TanStack5w ago
extended-salmon

Can I create a form using loop from zod schemas automatically in Tanstack form?

Hi, I'm start learning about Tanstack form today, I want to create a form that have different fields generated from already zod schemas using for loop, for example if I have 100 schema and want to create a form from those shemas using for loop. Is it possible and easy using Tanstack form?
3 Replies
foreign-sapphire
foreign-sapphire5w ago
well, zod generates input and output types which you can read and create forms with. See z.input<typeof yourSchema> as example. from that, you can create defaultValues that satisfy the condition and use those in the form hook:
const yourSchema = z.object({ /* ... */ })

// note: NOT infer. input is not the same as infer.
const defaultValues: z.input<typeof yourSchema> = { /* ... */ }

const form = useForm({
defaultValues,
validators: {
// add the zod schema in here, depending on what you want to do
}
})
const yourSchema = z.object({ /* ... */ })

// note: NOT infer. input is not the same as infer.
const defaultValues: z.input<typeof yourSchema> = { /* ... */ }

const form = useForm({
defaultValues,
validators: {
// add the zod schema in here, depending on what you want to do
}
})
extended-salmon
extended-salmonOP5w ago
@Luca | LeCarbonator , thank you but I edited the question, I really want to create form field automated from schemas with for loop.
foreign-sapphire
foreign-sapphire5w ago
Zod schemas have a shape property which you can iterate through to generate the default values you need so assuming you always have the same default values (empty strings for strings, 0 for numbers, today for dates etc.), yeah you can generate that possible with tanstack form? absolutely. Easy? Not sure.

Did you find this page helpful?