React Hook Form
Build forms with React Hook Form, Zod and the Field component.
React Hook Form holds the form state, a Zod schema validates it, and Field lays out each control with its label and error.
Demo
The form records a lab observation with a summary and details. Submit it to see the schema's errors or the values it accepted.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { Controller, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { InputGroup, InputGroupAddon, InputGroupText } from "@/components/ui/input-group"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const formSchema = z.object({
title: z
.string()
.min(5, "Use at least 5 characters for the summary.")
.max(32, "Keep the summary to 32 characters or fewer."),
description: z
.string()
.min(20, "Write at least 20 characters of detail.")
.max(100, "Keep the details to 100 characters or fewer."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfDemo() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { title: "", description: "" },
})
return (
<Card xstyle={widths.md}>
<CardHeader>
<CardTitle>Lab Observation</CardTitle>
<CardDescription>Record what you saw so the next run can repeat it.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-demo" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<FieldGroup>
<Controller
name="title"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Summary</FieldLabel>
<Input
{...field}
id="form-rhf-demo-title"
placeholder="Pendulum period drifts upward"
autoComplete="off"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<Controller
name="description"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Details</FieldLabel>
<InputGroup>
<Input
{...field}
id="form-rhf-demo-description"
placeholder="The period grew by two percent after ten minutes of swinging."
autoComplete="off"
/>
<InputGroupAddon align="inline-end">
<InputGroupText>{field.value.length}/100</InputGroupText>
</InputGroupAddon>
</InputGroup>
<FieldDescription>
Note the setup, what you expected, and what you measured instead.
</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
</FieldGroup>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
<Button type="submit" form="form-rhf-demo">
Submit
</Button>
</Field>
</CardFooter>
</Card>
)
}The demo leaves out required, minLength and the other native attributes, so
every error you see comes from the schema. Keep them in a real form. The browser
checks them even when JavaScript hasn't loaded.
Installation
pnpm add react-hook-form @hookform/resolvers zodnpm install react-hook-form @hookform/resolvers zodyarn add react-hook-form @hookform/resolvers zodbun add react-hook-form @hookform/resolvers zodThe examples also use Field, Fieldset, Input, Input Group, Checkbox, Button and Card.
One field
Every field in this guide has the same shape. Controller connects one control
to the form and gives you that control's state. Field displays it.
<Controller
name="title"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Summary</FieldLabel>
<Input {...field} placeholder="Pendulum period drifts upward" autoComplete="off" />
<FieldDescription>Describe the observation in a few words.</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>Pass fieldState.invalid to Field once. The label, the control and the error
all read it from there. FieldLabel labels the control without an htmlFor.
FieldError renders nothing while fieldState.error is undefined, so it needs
no condition around it.
Build the form
Write the schema
The messages you write here are the ones FieldError shows.
import * as z from "zod"
const formSchema = z.object({
title: z
.string()
.min(5, "Use at least 5 characters for the summary.")
.max(32, "Keep the summary to 32 characters or fewer."),
description: z
.string()
.min(20, "Write at least 20 characters of detail.")
.max(100, "Keep the details to 100 characters or fewer."),
})Create the form
Pass the schema to useForm through zodResolver. Give every field a default
value. Without one the input starts uncontrolled, and React warns when its first
value arrives.
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
type FormValues = z.infer<typeof formSchema>
export function ObservationForm() {
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { title: "", description: "" },
})
function onSubmit(data: FormValues) {
console.log(data)
}
return <form onSubmit={form.handleSubmit(onSubmit)}>{/* Build the form here */}</form>
}handleSubmit runs the schema and calls onSubmit only when it passes, with the
parsed values. When it fails, each Controller receives its field's error.
Add the fields
Add one Controller per field. Each one renders a Field.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { Controller, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { InputGroup, InputGroupAddon, InputGroupText } from "@/components/ui/input-group"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const formSchema = z.object({
title: z
.string()
.min(5, "Use at least 5 characters for the summary.")
.max(32, "Keep the summary to 32 characters or fewer."),
description: z
.string()
.min(20, "Write at least 20 characters of detail.")
.max(100, "Keep the details to 100 characters or fewer."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfDemo() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { title: "", description: "" },
})
return (
<Card xstyle={widths.md}>
<CardHeader>
<CardTitle>Lab Observation</CardTitle>
<CardDescription>Record what you saw so the next run can repeat it.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-demo" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<FieldGroup>
<Controller
name="title"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Summary</FieldLabel>
<Input
{...field}
id="form-rhf-demo-title"
placeholder="Pendulum period drifts upward"
autoComplete="off"
/>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<Controller
name="description"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Details</FieldLabel>
<InputGroup>
<Input
{...field}
id="form-rhf-demo-description"
placeholder="The period grew by two percent after ten minutes of swinging."
autoComplete="off"
/>
<InputGroupAddon align="inline-end">
<InputGroupText>{field.value.length}/100</InputGroupText>
</InputGroupAddon>
</InputGroup>
<FieldDescription>
Note the setup, what you expected, and what you measured instead.
</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
</FieldGroup>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
<Button type="submit" form="form-rhf-demo">
Submit
</Button>
</Field>
</CardFooter>
</Card>
)
}When validation runs
By default nothing validates until the first submit. After that, fields
re-validate on every change. Set mode to validate earlier.
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { title: "", description: "" },
mode: "onTouched",
})| Mode | Validates |
|---|---|
"onSubmit" | On submit. The default. |
"onBlur" | When a field loses focus. |
"onChange" | On every change. |
"onTouched" | On a field's first blur, then on every change. |
"all" | On blur and on change. |
Other controls
Field wraps every control the same way. What changes is how the control takes
its value. Textarea takes the spread, like Input. Select and RadioGroup
take value and onValueChange. Switch and Checkbox take checked and
onCheckedChange.
Input
Spread field onto Input. It carries name, value, onChange,
onBlur and ref.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { Controller, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const formSchema = z.object({
username: z
.string()
.min(3, "Use at least 3 characters.")
.max(10, "Use 10 characters or fewer.")
.regex(/^[a-zA-Z0-9_]+$/, "Use only letters, numbers and underscores."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfInput() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { username: "" },
})
return (
<Card xstyle={widths.md}>
<CardHeader>
<CardTitle>Account</CardTitle>
<CardDescription>Choose the name other researchers see.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-input" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<FieldGroup>
<Controller
name="username"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Username</FieldLabel>
<Input
{...field}
id="form-rhf-input-username"
placeholder="lovelace"
autoComplete="username"
/>
<FieldDescription>
Shown on your notebook entries. Use 3 to 10 letters, numbers or underscores.
</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
</FieldGroup>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
<Button type="submit" form="form-rhf-input">
Save
</Button>
</Field>
</CardFooter>
</Card>
)
}Checkbox
Checkbox reports changes through onCheckedChange, not onChange, so
spreading field doesn't work. Set checked from field.value and pass field.onChange
to onCheckedChange. For a set of checkboxes the value is an array, and each box
adds or removes its own id.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { Controller, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import {
Field,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
FieldSeparator,
} from "@/components/ui/field"
import { FieldsetLegend, Fieldset } from "@/components/ui/fieldset"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const tasks = [
{ id: "push", label: "Push notifications" },
{ id: "email", label: "Email notifications" },
]
const formSchema = z.object({
responses: z.boolean(),
tasks: z.array(z.string()).min(1, "Choose at least one way to hear about comments."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfCheckbox() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { responses: true, tasks: [] },
})
return (
<Card xstyle={widths.md}>
<CardHeader>
<CardTitle>Notifications</CardTitle>
<CardDescription>Choose how the lab notebook reaches you.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-checkbox" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<FieldGroup>
<Controller
name="responses"
control={form.control}
render={({ field }) => (
<Fieldset>
<FieldsetLegend variant="label">Experiments</FieldsetLegend>
<FieldDescription>
Get notified when a long run finishes, such as a simulation or a sweep.
</FieldDescription>
<FieldGroup gap={3}>
<Field orientation="horizontal" disabled>
<Checkbox
id="form-rhf-checkbox-responses"
name={field.name}
checked={field.value}
onCheckedChange={field.onChange}
/>
<FieldLabel>Push notifications</FieldLabel>
</Field>
</FieldGroup>
</Fieldset>
)}
/>
<FieldSeparator />
<Controller
name="tasks"
control={form.control}
render={({ field, fieldState }) => (
<Fieldset>
<FieldsetLegend variant="label">Comments</FieldsetLegend>
<FieldDescription>
Get notified when someone replies to an entry you wrote.
</FieldDescription>
<FieldGroup gap={3}>
{tasks.map((task) => (
<Field key={task.id} orientation="horizontal" invalid={fieldState.invalid}>
<Checkbox
id={`form-rhf-checkbox-${task.id}`}
name={field.name}
checked={field.value.includes(task.id)}
onCheckedChange={(checked) =>
field.onChange(
checked
? [...field.value, task.id]
: field.value.filter((value) => value !== task.id),
)
}
/>
<FieldLabel>{task.label}</FieldLabel>
</Field>
))}
</FieldGroup>
<FieldError errors={[fieldState.error]} />
</Fieldset>
)}
/>
</FieldGroup>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
<Button type="submit" form="form-rhf-checkbox">
Save
</Button>
</Field>
</CardFooter>
</Card>
)
}<Controller
name="tasks"
control={form.control}
render={({ field, fieldState }) => (
<Fieldset>
<FieldsetLegend variant="label">Comments</FieldsetLegend>
<FieldDescription>Get notified when someone replies to an entry you wrote.</FieldDescription>
<FieldGroup gap={3}>
{tasks.map((task) => (
<Field key={task.id} orientation="horizontal" invalid={fieldState.invalid}>
<Checkbox
id={`form-rhf-checkbox-${task.id}`}
name={field.name}
checked={field.value.includes(task.id)}
onCheckedChange={(checked) =>
field.onChange(
checked
? [...field.value, task.id]
: field.value.filter((value) => value !== task.id),
)
}
/>
<FieldLabel>{task.label}</FieldLabel>
</Field>
))}
</FieldGroup>
<FieldError errors={[fieldState.error]} />
</Fieldset>
)}
/>The error belongs to the set, not to one box, so it goes after the FieldGroup,
inside the Fieldset.
Choice cards
A choice card is a FieldLabel wrapped around its Field. The label doesn't
know the control's state, so pass checked to it. This form also has a required
agreement checkbox. Its error is inside FieldContent, under the description.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { Controller, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import {
Field,
FieldContent,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
FieldSeparator,
FieldTitle,
} from "@/components/ui/field"
import { FieldsetLegend, Fieldset } from "@/components/ui/fieldset"
import { Input } from "@/components/ui/input"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const addons = [
{ id: "plotting", title: "Plotting", description: "Charts and fitted curves for every run" },
{ id: "archive", title: "Archive", description: "Raw data kept for ten years" },
{ id: "review", title: "Peer Review", description: "A second reader for each report" },
]
const formSchema = z.object({
addons: z
.array(z.string())
.min(1, "Choose at least one add-on")
.max(2, "Choose no more than 2 add-ons"),
billingEmail: z.email("Enter a valid email address."),
terms: z.boolean().refine((value) => value, "Agree to the usage policy to continue."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfComplex() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { addons: [], billingEmail: "", terms: false },
})
return (
<Card xstyle={widths.sm}>
<CardHeader>
<CardTitle>Finish setting up your lab</CardTitle>
<CardDescription>Pick add-ons and where invoices should go.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-complex" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<FieldGroup>
<Controller
name="addons"
control={form.control}
render={({ field, fieldState }) => (
<Fieldset>
<FieldsetLegend variant="label">Add-ons</FieldsetLegend>
<FieldDescription>Pick up to two to add to your plan.</FieldDescription>
<FieldGroup gap={3}>
{addons.map((addon) => {
const checked = field.value.includes(addon.id)
return (
<FieldLabel
key={addon.id}
htmlFor={`form-rhf-complex-${addon.id}`}
checked={checked}
>
<Field orientation="horizontal" invalid={fieldState.invalid}>
<FieldContent>
<FieldTitle>{addon.title}</FieldTitle>
<FieldDescription>{addon.description}</FieldDescription>
</FieldContent>
<Checkbox
id={`form-rhf-complex-${addon.id}`}
name={field.name}
checked={checked}
onCheckedChange={(next) => {
field.onChange(
next
? [...field.value, addon.id]
: field.value.filter((value) => value !== addon.id),
)
field.onBlur()
}}
/>
</Field>
</FieldLabel>
)
})}
</FieldGroup>
<FieldError errors={[fieldState.error]} />
</Fieldset>
)}
/>
<FieldSeparator />
<Controller
name="billingEmail"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Billing Email</FieldLabel>
<Input
{...field}
id="form-rhf-complex-billing-email"
type="email"
placeholder="billing@example.com"
autoComplete="email"
/>
<FieldDescription>Receipts and invoices go here.</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
)}
/>
<FieldSeparator />
<Controller
name="terms"
control={form.control}
render={({ field, fieldState }) => (
<Field orientation="horizontal" invalid={fieldState.invalid}>
<Checkbox
id="form-rhf-complex-terms"
name={field.name}
checked={field.value}
onCheckedChange={field.onChange}
/>
<FieldContent>
<FieldLabel>Agree to the usage policy</FieldLabel>
<FieldDescription>
The policy covers how lab data is stored and shared.
</FieldDescription>
<FieldError errors={[fieldState.error]} />
</FieldContent>
</Field>
)}
/>
</FieldGroup>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field>
<Button type="submit" form="form-rhf-complex">
Save Preferences
</Button>
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
</Field>
</CardFooter>
</Card>
)
}Resetting the form
form.reset() returns every field to its default value and clears the errors.
<Button type="button" variant="outline" onClick={() => form.reset()}>
Reset
</Button>Array fields
useFieldArray manages a list the user can add to and remove from.
"use client"
import { useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import * as stylex from "@stylexjs/stylex"
import { XIcon } from "@phosphor-icons/react/dist/csr/X"
import { Controller, useFieldArray, useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Field, FieldContent, FieldDescription, FieldError, FieldGroup } from "@/components/ui/field"
import { FieldsetLegend, Fieldset } from "@/components/ui/fieldset"
import { Input } from "@/components/ui/input"
import { InputGroup, InputGroupAddon, InputGroupButton } from "@/components/ui/input-group"
import { color, font, leading, radius, space, text } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"
const formSchema = z.object({
emails: z
.array(z.object({ address: z.email("Enter a valid email address.") }))
.min(1, "Invite at least one person.")
.max(5, "Send no more than 5 invitations at once."),
})
type FormValues = z.infer<typeof formSchema>
const styles = stylex.create({
output: {
marginBlockStart: space.s4,
overflowX: "auto",
borderRadius: radius.md,
backgroundColor: color.muted,
padding: space.s3,
fontFamily: font.mono,
fontSize: text.xs,
lineHeight: leading.xs,
},
})
export default function FormRhfArray() {
const [submitted, setSubmitted] = useState<FormValues | null>(null)
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: { emails: [{ address: "" }, { address: "" }] },
})
const { fields, append, remove } = useFieldArray({ control: form.control, name: "emails" })
return (
<Card xstyle={widths.md}>
<CardHeader>
<CardTitle>Collaborators</CardTitle>
<CardDescription>Invite people to edit this notebook.</CardDescription>
</CardHeader>
<CardContent>
<form id="form-rhf-array" onSubmit={form.handleSubmit((data) => setSubmitted(data))}>
<Fieldset>
<FieldsetLegend variant="label">Invite by email</FieldsetLegend>
<FieldDescription>Send up to 5 invitations at once.</FieldDescription>
<FieldGroup gap={4}>
{fields.map((item, index) => (
<Controller
key={item.id}
name={`emails.${index}.address`}
control={form.control}
render={({ field, fieldState }) => (
<Field orientation="horizontal" invalid={fieldState.invalid}>
<FieldContent>
<InputGroup>
<Input
{...field}
id={`form-rhf-array-email-${index}`}
aria-label={`Email ${index + 1}`}
placeholder="noether@example.com"
type="email"
autoComplete="email"
/>
{fields.length > 1 && (
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
variant="ghost"
size="icon-xs"
onClick={() => remove(index)}
aria-label={`Remove email ${index + 1}`}
>
<XIcon aria-hidden="true" />
</InputGroupButton>
</InputGroupAddon>
)}
</InputGroup>
<FieldError errors={[fieldState.error]} />
</FieldContent>
</Field>
)}
/>
))}
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ address: "" })}
disabled={fields.length >= 5}
>
Add Email Address
</Button>
</Field>
</FieldGroup>
</Fieldset>
</form>
{submitted && (
<pre {...stylex.props(styles.output)}>{JSON.stringify(submitted, null, 2)}</pre>
)}
</CardContent>
<CardFooter>
<Field orientation="horizontal">
<Button
type="button"
variant="outline"
onClick={() => {
form.reset()
setSubmitted(null)
}}
>
Reset
</Button>
<Button type="submit" form="form-rhf-array">
Save
</Button>
</Field>
</CardFooter>
</Card>
)
}The hook
useFieldArray returns the current fields, plus append and remove.
import { useFieldArray, useForm } from "react-hook-form"
export function ExampleForm() {
const form = useForm({
// ... form config
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "emails",
})
}Rows
Wrap the list in a Fieldset with a legend, then map over fields with one
Controller per row. Key each row by item.id, not by index. With index keys,
removing a row leaves its state on the row that takes its place.
{
fields.map((item, index) => (
<Controller
key={item.id}
name={`emails.${index}.address`}
control={form.control}
render={({ field, fieldState }) => (
<Field orientation="horizontal" invalid={fieldState.invalid}>
<FieldContent>
<InputGroup>
<Input
{...field}
id={`form-rhf-array-email-${index}`}
aria-label={`Email ${index + 1}`}
placeholder="noether@example.com"
type="email"
autoComplete="email"
/>
{/* Remove button */}
</InputGroup>
<FieldError errors={[fieldState.error]} />
</FieldContent>
</Field>
)}
/>
))
}Adding and removing rows
Call append with a new row's default value, and disable the button at the
schema's limit.
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ address: "" })}
disabled={fields.length >= 5}
>
Add Email Address
</Button>Call remove with the row's index. Render the button only while more than one
row remains, so the user can't empty the list.
{
fields.length > 1 && (
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
variant="ghost"
size="icon-xs"
onClick={() => remove(index)}
aria-label={`Remove email ${index + 1}`}
>
<X />
</InputGroupButton>
</InputGroupAddon>
)
}Validating the list
The inner schema validates each row. .min and .max validate the list's
length.
const formSchema = z.object({
emails: z
.array(z.object({ address: z.email("Enter a valid email address.") }))
.min(1, "Invite at least one person.")
.max(5, "Send no more than 5 invitations at once."),
})A length error belongs to the array, not to a row, so the resolver puts it on
root. Render it after the FieldGroup. The demo never shows one, because its
buttons keep the list between one and five rows.
<FieldError errors={[form.formState.errors.emails?.root]} />Without React Hook Form
Form handles native validation and server errors
without React Hook Form. Pass server messages through errors, keyed by field name. Editing a field
clears its server error.
"use client"
import { useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Form } from "@/components/ui/form"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
const styles = stylex.create({ form: { width: "20rem" } })
export default function FormDemo() {
const [errors, setErrors] = useState<Record<string, string>>({})
const [submitted, setSubmitted] = useState(false)
return (
<Form
errors={errors}
xstyle={styles.form}
onFormSubmit={(values) => {
if (values.username === "admin") {
setErrors({ username: "This username is taken." })
setSubmitted(false)
} else {
setErrors({})
setSubmitted(true)
}
}}
>
<FieldGroup>
<Field name="username">
<FieldLabel>Username</FieldLabel>
<Input required placeholder="Try admin" />
<FieldError />
</Field>
<Button type="submit">Save</Button>
{submitted && <output>Profile saved.</output>}
</FieldGroup>
</Form>
)
}