docs/forms/react-hook-form
Sections
Components
Utilities
Forms
Hooks
Copy Markdown
Build forms in React using React Hook Form and Zod.
This guide will cover building forms using the Field component, adding schema validation with Zod, handling errors, ensuring accessibility, and more.
We’ll build a form with a text input and textarea. When you submit, the form data is validated and any errors will be shown.
Browser validation disabled
For the purposes of this demo, browser validation is disabled to illustrate schema validation. In production, keep native validation enabled when appropriate.
PreviewCode
Bug Report
Help us improve by reporting bugs you encounter.
Bug Title
Description
0/100 characters
Include steps to reproduce, expected behavior, and what actually happened.
ResetSubmit
This form uses React Hook Form for state and Zod for validation. We'll build forms using the Field component, which gives you complete flexibility over the markup and styling.
Controller component for controlled inputs.Field components for building accessible forms.resolver.Typical structure: wrap each field with Controller, and the Field component.
<form onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
name="title"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Bug Title</FieldLabel>
<Input
{...field}
placeholder="Login button not working on mobile"
autoComplete="off"
/>
<FieldDescription>
Provide a concise title for your bug report.
</FieldDescription>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</FieldGroup>
<Button type="submit">Submit</Button>
</form>
Define your form shape with a Zod schema.
Note: React Hook Form supports other Standard Schema libraries; Zod is used here for clarity.
form.tsx
import * as z from "zod"
const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
})
Create the form with useForm from React Hook Form and pass your schema to the resolver option.
form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
const formSchema = z.object({
// ...
});
export const BugReportForm = () => {
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
},
});
const onSubmit = (data: z.infer<typeof formSchema>) => {
console.log(data);
}
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
</form>
);
};
Build the form using the Controller from React Hook Form and the Shark Field.
Expand
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@registry/react/components/toast";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardFooter,
CardHeader,
} from "@/components/ui/card";
import {
Field,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
InputGroup,
InputGroupAddon,
InputGroupText,
InputGroupTextarea,
} from "@/components/ui/input-group";
const formSchema = z.object({
title: z
.string()
.min(5, "Bug title must be at least 5 characters.")
.max(32, "Bug title must be at most 32 characters."),
description: z
.string()
.min(20, "Description must be at least 20 characters.")
.max(100, "Description must be at most 100 characters."),
});
export const BugReportForm = () => {
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
},
});
const onSubmit = (data: z.infer<typeof formSchema>) => {
toast.info({
id: "bug-report-submitted",
title: "Bug submitted",
description: (
<pre className="mt-2">
<code>{JSON.stringify(data, null, 2)}</code>
</pre>
),
});
};
return (
<Card asChild className="w-full sm:max-w-md">
<form onSubmit={form.handleSubmit(onSubmit)}>
<CardHeader
description="Help us improve by reporting bugs you encounter."
title="Bug Report"
/>
<CardContent>
<FieldGroup>
<Controller
control={form.control}
name="title"
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Bug Title</FieldLabel>
<Input
{...field}
autoComplete="off"
placeholder="Login button not working on mobile"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
control={form.control}
name="description"
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Description</FieldLabel>
<InputGroup>
<InputGroupTextarea
{...field}
className="min-h-24 resize-none"
placeholder="I'm having an issue with the login button on mobile."
rows={6}
/>
<InputGroupAddon align="block-end">
<InputGroupText className="tabular-nums">
{field.value.length}/100 characters
</InputGroupText>
</InputGroupAddon>
</InputGroup>
<FieldDescription>
Include steps to reproduce, expected behavior, and what
actually happened.
</FieldDescription>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</FieldGroup>
</CardContent>
<CardFooter>
<Button onClick={() => form.reset()} variant="outline">
Reset
</Button>
<Button type="submit">Submit</Button>
</CardFooter>
</form>
</Card>
);
};
Expand
That's it. You now have a fully accessible form with client-side validation.
When you submit the form, the onSubmit function will be called with the validated form data. If the form is invalid, React Hook Form will display the errors on field.state.error for FieldError.
React Hook Form validates your form data using the Zod schema. Define a schema and pass it to the resolver option of the useForm hook.
example-form.tsx
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
const formSchema = z.object({
title: z.string(),
description: z.string().optional(),
})
export const ExampleForm = () => {
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
title: "",
description: "",
},
})
}
Configure when validation runs via the mode option:
form.tsx
const form = useForm({
resolver: zodResolver(formSchema),
mode: "onChange",
})
| Mode | Description |
|---|---|
"onChange" | Validation triggers on every change. |
"onBlur" | Validation triggers on blur. |
"onSubmit" | Validation triggers on submit (default). |
"onTouched" | Validation triggers on first blur, then on every change. |
"all" | Validation triggers on blur and change. |
Display errors next to the field using FieldError. For styling and accessibility:
invalid prop to the Field component.invalid prop to the form control such as Input, Checkbox, etc.form.tsx
<Controller
name="email"
control={form.control}
render={({ field, fieldState }) => (
<Field invalid={fieldState.invalid}>
<FieldLabel>Email</FieldLabel>
<Input {...field} type="email" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
Input component.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Profile Settings
Update your profile information below.
Username
This is your public display name. Must be between 3 and 10 characters. Must only contain letters, numbers, and underscores.
ResetSave
Textarea component.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Personalization
Customize your experience by telling us more about yourself.
More about you
Tell us more about yourself. This will be used to help us personalize your experience.
ResetSave
NativeSelect component.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Language Preferences
Select your preferred spoken language.
Spoken Language
For best results, select the language you speak.
AutoEnglishSpanishFrenchGermanItalianChineseJapanese
ResetSave
field.value and field.onChange to Select.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Language Preferences
Select your preferred spoken language.
Spoken Language
For best results, select the language you speak.
Select
AutoEnglishSpanishFrenchGermanItalianChineseJapanese
ResetSave
field.value and field.onChange to Checkbox.invalid prop to the Field component and pass the error message to the FieldError component.data-slot="checkbox-group" to the FieldGroup component for proper styling and spacing.PreviewCode
Notifications
Manage your notification preferences.
Responses
Get notified for requests that take time, like research or image generation.
Push notifications
Tasks
Get notified when tasks you've created have updates.
Push notifications
Email notifications
ResetSave
field.value and field.onChange to RadioGroup.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Subscription Plan
See pricing and features for each plan.
Plan
You can upgrade or downgrade your plan at any time.
Starter (100K tokens/month)
For everyday use with basic features.
Pro (1M tokens/month)
For advanced AI usage with more features.
Enterprise (Unlimited tokens)
For large teams and heavy usage.
ResetSave
field.value and field.onChange to Switch.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Security Settings
Manage your account security preferences.
Multi-factor authentication
Enable multi-factor authentication to secure your account.
ResetSave
field.value and field.onChange to NumberInput.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Salary expectations
Share your target gross annual salary in EUR.
Expected annual salary
€
EUR
ResetSave
field.value and field.onChange to Slider.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Listings filter
Set a price range so we only show results in your budget.
Price range$0 - $10000
Drag each thumb to set the lower and upper bound.
ResetApply
field.value and field.onChange to Combobox.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Role setup
Tell us which team you work with most so we can tailor workflows.
Primary department
Type to filter the list, then pick one option.
ResetSave
field.value and field.onChange to Autocomplete.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Tech stack
Select the technology you're most familiar with.
Primary technology
Type to filter the list, then pick one option.
ResetSave
field.value and field.onChange to DatePicker.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Scheduling
Pick a day that works for a first-round interview. We will confirm by email.
Preferred interview date
Pick a date
ResetSave
field.value and field.onChange to InputOTP.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Account recovery
Enter one of your single-use backup codes if you cannot access your authenticator app.
Backup code
Codes can only be used once.
ResetSave
field.value and field.onChange to Rating.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Quick feedback
Help us improve by sharing how likely you are to recommend Shark UI to a colleague.
How useful is this project?
1 = not likely, 5 = very likely.
ResetSave
field.value and field.onChange to FileUpload.invalid prop to the Field component and pass the error message to the FieldError component.PreviewCode
Application materials
Upload your résumé or CV.
Résumé
Accepted formats: PDF and Word documents.
ResetSave
Here is an example of a more complex form with multiple fields and validation.
PreviewCode
You're almost there!
Choose your subscription plan and billing period.
Subscription plan
Choose your subscription plan.
Basic
For individuals and small teams
Pro
For businesses with higher demands
Billing period
Select
MonthlyYearly
Choose how often you want to be billed.
Add-ons
Select additional features you'd like to include.
Analytics
Advanced analytics and reporting
Backup
Automated daily backups
Priority Support
24/7 premium customer support
Email notifications
Receive email updates about your subscription.
Save preferencesReset
Use form.reset() to reset the form to its default values.
<Button type="button" variant="outline" onClick={() => form.reset()}>
Reset
</Button>
React Hook Form provides a useFieldArray hook for managing dynamic array fields. This is useful when you need to add or remove fields dynamically.
PreviewCode
Contact emails
Manage your contact email addresses.
Email addresses
Add up to 5 email addresses where we can contact you.
Add email address
ResetSave
Use the useFieldArray hook to manage array fields. It provides fields, append, and remove methods.
form.tsx
import { useFieldArray, useForm } from "react-hook-form";
export const ExampleForm = () => {
const form = useForm({
// ... form config
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "emails",
});
}
Wrap your array fields in a FieldSet with a FieldLegend and FieldDescription.
form.tsx
<FieldSet className="gap-4">
<FieldLegend variant="label">Email Addresses</FieldLegend>
<FieldDescription>
Add up to 5 email addresses where we can contact you.
</FieldDescription>
<FieldGroup className="gap-4"></FieldGroup>
</FieldSet>
Map over the fields array and use Controller for each item. Make sure to use field.id as the key.
form.tsx
{
fields.map((field, index) => (
<Controller
key={field.id}
name={`emails.${index}.address`}
control={form.control}
render={({ field: controllerField, fieldState }) => (
<Field invalid={fieldState.invalid} orientation="horizontal">
<FieldContent>
<InputGroup>
<InputGroupInput
{...controllerField}
id={`form-rhf-array-email-${index}`}
aria-invalid={fieldState.invalid}
placeholder="[email protected]"
type="email"
autoComplete="email"
/>
</InputGroup>
<FieldError>{fieldState.error?.message}</FieldError>
</FieldContent>
</Field>
)}
/>
))}
Use the append method to add new items to the array.
form.tsx
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ address: "" })}
disabled={fields.length >= 5}
>
Add Email Address
</Button>
Use the remove method to remove items from the array. Add the remove button conditionally.
form.tsx
{
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 />
</InputGroupButton>
</InputGroupAddon>
)}
}
Use Zod's array method to validate array fields.
form.tsx
const formSchema = z.object({
emails: z
.array(
z.object({
address: z.string().email("Enter a valid email address."),
})
)
.min(1, "Add at least one email address.")
.max(5, "You can add up to 5 email addresses."),
});
[
Previous page
Formisch ](/docs/forms/formisch)[
Next page
TanStack Form ](/docs/forms/tanstack-form)
On This Page
DemoApproachAnatomyFormCreate a schemaSetupBuildDoneValidationClient-sideModesDisplaying ErrorsDifferent types of fieldsInputTextareaNativeSelectSelectCheckboxRadio groupSwitchNumberInputSliderComboboxAutocompleteDate PickerInput OTPRatingFile UploadComplex FormsResetting the FormArray FieldsUsing useFieldArrayArray Field StructureController Pattern for Array ItemsAdding ItemsRemoving ItemsArray Validation