Sub topic 12
Repeating fields with useFieldArray
This chapter assumes you can already build a form with useForm, register, and handleSubmit, and that you can connect a Zod schema through zodResolver. Here you will manage a list of inputs that the user can grow and shrink.
Why a plain loop is not enough
Some forms need a variable number of rows: line items, phone numbers, tags. You could map over an array held in your own state. That would bypass React Hook Form, so the rows would lose registration, validation, and error tracking.
useFieldArray solves this. It owns the list structure and gives you helpers to change it, while register still handles each input.
The schema
Describe the list with z.array. The inner object validates each row. The .min(1, ...) on the array validates the list as a whole.
A working form
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const listSchema = z.object({
items: z
.array(z.object({ name: z.string().min(1, "Name is required") }))
.min(1, "Add at least one item"),
});
type ListValues = z.infer<typeof listSchema>;
export function ItemsForm() {
const {
control,
register,
handleSubmit,
formState: { errors },
} = useForm<ListValues>({
resolver: zodResolver(listSchema),
defaultValues: { items: [{ name: "" }] },
});
const { fields, append, remove } = useFieldArray({ control, name: "items" });
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`items.${index}.name`)} />
{errors.items?.[index]?.name && (
<p role="alert">{errors.items[index]?.name?.message}</p>
)}
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={() => append({ name: "" })}>
Add item
</button>
<button type="submit">Save</button>
</form>
);
}How it works
controllinks the array to the form. Pass it touseFieldArrayalong with the array'sname.fieldsis the list to render. Each entry has a generatedid.appendandremoveadd and delete rows.insert,swap,move, andupdatealso exist.- Each input registers with an indexed path such as
items.0.name. The template literal keeps the path type-checked againstListValues. - Errors follow the same shape as the data, so a row's error is at
errors.items?.[index]?.name.
Common mistakes
- Missing default values. Give the array a starting value in
defaultValues. Appended rows should also be complete objects, such as{ name: "" }. - Reading
fieldsas current values.fieldscan lag behind what the user typed. UsewatchorgetValueswhen you need live values. - Missing the list-level error. The "Add at least one item" message belongs to the array, not to a row. In recent versions of React Hook Form it appears at
errors.items?.root?.message. Render it separately from the row errors. - Plain string arrays. Field arrays expect objects. Use
{ name: string }[]instead ofstring[].
To pre-fill the list from saved data, pass the rows in `defaultValues` or call `reset` with them. `useFieldArray` picks up the new rows.Exercise
A user removes the first of three rows, but the remaining rows show the wrong text. The code uses key={index}. What is the cause, and what is the fix?
Show answer
React matches rows by key. With index keys, the DOM nodes keep their position instead of following their data, so they show stale input state. Use key={field.id}, which stays attached to each row through removals.
Exercise
Where do you read the error for an empty name in the second row, and where do you read the error for an empty list?
Show answer
The row error is at errors.items?.[1]?.name?.message. The empty-list error is at errors.items?.root?.message in recent React Hook Form versions.