Automatically check that the field is re ...

Automatically check that the field is required using React Hook Form and Zod

Aug 20, 2024

There are several unresolved issues regarding Shadcn Form component in case of automatic field optionality check:

The solution is pretty similar:

  • To know that zod field is optional, use <zodField> instanseof ZodOptional construction.

  • To access object field, use <zodObject>.shape.<field>

  • To access object field if object is an array element, use<zodArray>._def.type.shape.<field>

To make it elegant, use the provided code snippet. Of course, you could provide the schema using react context. Other required stuff already exists inside generated by Shadcn file (ui.shadcn.com/docs/components/form).

Important: the result might be unexpected with difficult schemas that include recursions or conditions.

image

Ti piace questo post?

Offri un libro a Boris Shuliak

Altro da Boris Shuliak