Form
Field composition for React Hook Form that lays out label, control, description and error message, and wires their accessibility attributes.
Press “Cadastrar processo” with the form empty to see the validation messages.
When to use
- For every form that validates input: React Hook Form owns the state and Zod the rules.
- To get consistent spacing, labels, descriptions and error messages across forms.
When not to use
- A single field with no validation, such as a search box. Use Input on its own.
- Forms that do not use React Hook Form. The parts read the form from context, so they only work inside
Form. - Settings that apply on change. Use Switch or Checkbox without a form.
Anatomy
Form is React Hook Form’s FormProvider. Spread the object returned by
useForm() into it. Each field is a FormField that renders a FormItem.
| Part | Role |
|---|---|
Form |
Provides the form to every part below. Spread {...form} into it. |
FormField |
Connects one field by name and passes field and fieldState to render. |
FormItem |
Groups label, control and messages, and generates the ids that link them. |
FormLabel |
The field name, linked to the control. required adds an asterisk. |
FormControl |
Wraps the control and sets its id, aria-invalid and aria-describedby. |
FormDescription |
Helper text under the control. |
FormMessage |
The validation error from the schema. Renders nothing when there is no error. |
Examples
Form with validation
Rules come from a Zod schema through zodResolver. The Input gets
variant="error" from fieldState.error, so the border and the message agree.
Showing errors
The same form, validated as it appears. Each FormMessage shows the message
from the schema, and FormControl marks the control aria-invalid.
Content
- Write messages as the fix, not the problem: “Informe o número do processo.”, “Use o formato NNNNNNN-DD.AAAA.J.TR.OOOO.”
- Mark required fields with
requiredonFormLabeland leave optional ones unmarked, adding “Opcional” to the description. - Use
FormDescriptionfor rules the user needs before typing, andFormMessagefor what went wrong. - Name the submit button after the result: “Cadastrar processo”, not “Enviar”.
Accessibility
FormItemgenerates one id and derivesformItemId, the description id and the message id from it, soFormLabel(htmlFor),FormDescriptionandFormMessagealways point at the right control.FormControlsetsid,aria-invalidandaria-describedbyon its child with Radix Slot. The child must be a single element that accepts them: Input, Textarea, Checkbox.- Add
noValidateto the<form>and let Zod produce the messages, so the browser does not show its own tooltips. - Errors are text next to the field, not color alone.
FormMessageis not a live region, so move focus to the first invalid field on submit failure. React Hook Form does this by default throughshouldFocusError. - Controls that wrap their own label or message, such as Input with the
labelprop, duplicate whatFormLabelandFormMessagealready provide. Use the bare control.
Code
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@repo/ui/form";
import { Input } from "@repo/ui/input";
const schema = z.object({
caseNumber: z.string().min(1, "Informe o número do processo."),
});
const form = useForm({
defaultValues: { caseNumber: "" },
resolver: zodResolver(schema),
});
<Form {...form}>
<form noValidate onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="caseNumber"
render={({ field, fieldState }) => (
<FormItem>
<FormLabel required>Número do processo</FormLabel>
<FormControl>
<Input
{...field}
variant={fieldState.error ? "error" : "default"}
/>
</FormControl>
<FormDescription>Número único do CNJ.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>;
Props
Form is FormProvider from React Hook Form and takes the return value of useForm().
Form| Prop | Type | Default | Description |
|---|---|---|---|
control | Control | — | Not needed: `Form` spreads the `useForm()` return value |
handleSubmit | UseFormHandleSubmit | — | From `useForm()`. Wrap your submit handler with it |
FormField| Prop | Type | Default | Description |
|---|---|---|---|
control | Control | — | The `control` from `useForm()`. |
name | FieldPath | — | Field name. Must match a key of the schema. |
render | ({ field, fieldState, formState }) => ReactElement | — | Renders the field. Spread `field` on the control. |
defaultValue, rules, shouldUnregister | ControllerProps | — | Passed to React Hook Form's `Controller`. |
FormLabel| Prop | Type | Default | Description |
|---|---|---|---|
required | boolean | false | Adds a red asterisk after the label. |
size | "lg" | "md" | "sm" | "xs" | "xxs" | "sm" | Type size, as in Label. |
for | string | — | Overrides the generated control id. Rarely needed. |
FormMessage| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | — | Text shown when there is no error. The error message wins when there is one. |
FormItem takes native div attributes. FormControl takes the single child
that receives the accessibility attributes. FormDescription takes native p
attributes and renders Typography at paragraphXs.
Known issues
| Issue | Effect |
|---|---|
FormControl always lists the description id in aria-describedby, even without a FormDescription. |
The attribute points at an id that does not exist, which some validators flag. |
FormMessage is not a live region. |
Screen readers do not announce a new error when it appears, unless focus moves to the field. |
useFormField checks !fieldContext, but the context default is {}, so it never throws. |
Using FormLabel outside FormField fails later with a confusing React Hook Form error. |
FormControl does not set the control’s variant. |
Input and Textarea only turn red when you pass variant="error" yourself, as in the examples above. |