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

5 messages · Page 1 of 1 (latest)

median creek
#

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?

rich ledge
# median creek Hi, I'm start learning about Tanstack form today, I want to create a form that h...

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
   }
})
median creek
#

@rich ledge , thank you but I edited the question, I really want to create form field automated from schemas with for loop.

rich ledge
#

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