Sub topic 3
Transforms and Dynamic React Forms
Assume you know React hooks, TypeScript generics, HTML form events, and async/await. This chapter focuses on how validated values move through a form.
Transforms: input versus output
A Zod transform changes the value after validation. The browser still supplies a string, but your submit handler can receive another type.
const orderSchema = z.object({
quantity: z.string().regex(/^\d+$/).transform(Number),
});
type OrderInput = z.input<typeof orderSchema>; // { quantity: string }
type OrderOutput = z.output<typeof orderSchema>; // { quantity: number }
const form = useForm<OrderInput, unknown, OrderOutput>({
resolver: zodResolver(orderSchema),
});Use z.input for values entering the form and z.output for parsed values leaving it. This distinction prevents incorrect assumptions such as treating an input value as a number before submission.
Repeating fields
useFieldArray manages addable and removable rows. Register each row with its indexed path, and use the generated field.id as its React key.
const schema = z.object({
items: z.array(z.object({
name: z.string().min(1, "Name is required"),
})),
});
const { control, register } = useForm<z.infer<typeof schema>>({
resolver: zodResolver(schema),
defaultValues: { items: [{ name: "" }] },
});
const { fields, append, remove } = useFieldArray({ control, name: "items" });Controlled components
Use Controller when a UI component owns its value through value and onChange, such as a date picker or custom select.
<Controller
name="country"
control={control}
render={({ field, fieldState }) => (
<>
<CountrySelect {...field} />
{fieldState.error && <p role="alert">{fieldState.error.message}</p>}
</>
)}
/>Prefer register for ordinary native inputs. It has less wiring.
API errors and accessibility
Client validation does not replace server validation. Map a server failure onto the same error state:
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
setError("email", {
type: "server",
message: "This email is already registered",
});
}Give each input a label. Connect its error with aria-describedby, and use role="alert" so assistive technology announces it.
Watching values efficiently
watch() can make the whole form component re-render. Use useWatch in the smallest component that needs the value:
const country = useWatch({ control, name: "country" });This keeps unrelated fields from re-rendering when country changes.
Sharing and testing schemas
Put a shared Zod schema in a package used by the client and server. The client improves feedback, while the server remains the security boundary.
Test behavior with Testing Library: render the form, submit invalid data, assert the accessible error, then submit valid data and verify the API call.
Exercise
Why can a transformed field need both z.input and z.output?
Show answer
The browser supplies the input type, such as string, while the schema produces the output type, such as number.