Recipes
Forms & validation
ReactLoom fields show errors; your form library decides when. This recipe uses React Hook Form — the patterns carry over to any library or plain state.
A complete form
Submit it empty to see the error summary, then use its links to reach each field. The behaviour below is covered by tests that run React Hook Form against every control type in CI.
Invite a teammate
register for native controls, Controller for Select, RadioGroup and DatePicker.
import { DatePicker, type DateValue } from '@reactloom/dates';
import { Alert, Button, Checkbox, HStack, Input, Radio, RadioGroup, Select, Stack } from '@reactloom/ui';
import { useRef, useState } from 'react';
import { Controller, useForm, type FieldErrors } from 'react-hook-form';
interface Invite {
name: string;
email: string;
team: string | null;
role: string;
start: DateValue | null;
confirm: boolean;
}
const LABELS: Record<keyof Invite, string> = { name: 'Name', email: 'Email', team: 'Team', role: 'Role', start: 'Start date', confirm: 'Confirmation' };
// Stand-in for your API.
const invite = (data: Invite) =>
new Promise<{ ok: boolean; field?: keyof Invite; message?: string }>((resolve) =>
setTimeout(() => resolve(data.email.endsWith('@taken.com') ? { ok: false, field: 'email', message: 'This person has already been invited.' } : { ok: true }), 400),
);
export default function Example() {
const summaryRef = useRef<HTMLDivElement>(null);
const [problems, setProblems] = useState<Array<[keyof Invite, string]>>([]);
const [sent, setSent] = useState<string | null>(null);
const { register, control, handleSubmit, setError, setFocus, reset, formState: { errors, isSubmitting } } = useForm<Invite>({
defaultValues: { name: '', email: '', team: null, role: '', start: null, confirm: false },
// Long form: we show a summary and move focus to it instead of to the first field.
shouldFocusError: false,
});
const showSummary = (errs: FieldErrors<Invite>) => {
setProblems(Object.entries(errs).map(([k, v]) => [k as keyof Invite, String(v?.message ?? '')]));
requestAnimationFrame(() => summaryRef.current?.focus());
};
return (
<form
noValidate
style={{ width: '100%', maxWidth: 440 }}
onSubmit={handleSubmit(async (data) => {
setSent(null);
const result = await invite(data);
if (!result.ok && result.field) {
setError(result.field, { message: result.message }, { shouldFocus: true });
setProblems([]);
return;
}
setProblems([]);
setSent(data.email);
reset();
}, showSummary)}
>
<Stack gap="4">
{problems.length > 0 && (
<Alert
ref={summaryRef}
tabIndex={-1}
tone="danger"
title={`There ${problems.length === 1 ? 'is 1 problem' : `are ${problems.length} problems`} with the invitation`}
>
<ul style={{ margin: 0, paddingInlineStart: '1.1em' }}>
{problems.map(([field, message]) => (
<li key={field}>
<a
href={`#invite-${field}`}
onClick={(e) => {
e.preventDefault();
setFocus(field);
}}
>
{LABELS[field]}: {message}
</a>
</li>
))}
</ul>
</Alert>
)}
{sent && <Alert tone="success" live="polite" title={`Invitation sent to ${sent}`} />}
<Input id="invite-name" label="Name" autoComplete="name" {...register('name', { required: 'Enter their name.' })} error={errors.name?.message} />
<Input
id="invite-email"
label="Work email"
type="email"
autoComplete="email"
description="Try someone@taken.com to see a server error."
{...register('email', { required: 'Enter their work email.', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Enter an email like name@company.com.' } })}
error={errors.email?.message}
/>
<Controller
control={control}
name="team"
rules={{ required: 'Choose a team.' }}
render={({ field, fieldState }) => (
<Select
ref={field.ref}
id="invite-team"
name={field.name}
label="Team"
value={field.value}
onValueChange={field.onChange}
options={[{ value: 'design', label: 'Design' }, { value: 'eng', label: 'Engineering' }, { value: 'finance', label: 'Finance' }]}
error={fieldState.error?.message}
/>
)}
/>
<Controller
control={control}
name="role"
rules={{ required: 'Choose a role.' }}
render={({ field, fieldState }) => (
<RadioGroup legend="Role" name={field.name} value={field.value || null} onValueChange={field.onChange} error={fieldState.error?.message} orientation="horizontal">
{/* The group's ref is a <fieldset>; give the first radio to React Hook Form for focus. */}
<Radio ref={field.ref} id="invite-role" value="member" label="Member" />
<Radio value="admin" label="Admin" />
</RadioGroup>
)}
/>
<Controller
control={control}
name="start"
rules={{ required: 'Choose a start date.' }}
render={({ field, fieldState }) => (
<DatePicker id="invite-start" name={field.name} label="Start date" value={field.value} onValueChange={field.onChange} error={fieldState.error?.message} />
)}
/>
<Checkbox id="invite-confirm" label="They work for our company" {...register('confirm', { required: 'Confirm they work for your company.' })} error={errors.confirm?.message} />
<HStack gap="2">
{/* Never disable the submit button: people need to submit to find out what is wrong. */}
<Button type="submit" loading={isSubmitting}>
Send invitation
</Button>
<Button type="button" variant="secondary" onClick={() => { reset(); setProblems([]); setSent(null); }}>
Clear
</Button>
</HStack>
</Stack>
</form>
);
}register or Controller
register works with controls whose ref is a native input: Input, Textarea, PasswordInput, SearchInput, Checkbox, Switch. Controller is for composite controls with value / onValueChange: Select, Combobox, RadioGroup, SegmentedControl, NumberInput, Slider, and the date pickers. Pass field.ref so the field can receive focus — to the first Radio for a RadioGroup, whose own ref is a non-focusable <fieldset>.
// Native controls: spread register() — the ref reaches the <input>.
<Input label="Email" {...register('email', { required: 'Enter your email.' })} error={errors.email?.message} />
<Checkbox label="I accept the terms" {...register('terms', { required: 'Accept the terms.' })} error={errors.terms?.message} />
// Composite controls: Controller — map value/onChange to value/onValueChange.
<Controller
control={control}
name="country"
rules={{ required: 'Choose a country.' }}
render={({ field, fieldState }) => (
<Select ref={field.ref} name={field.name} label="Country" options={countries}
value={field.value} onValueChange={field.onChange} error={fieldState.error?.message} />
)}
/>Move focus to the problem
React Hook Form focuses the first invalid field in the order fields were registered, and Controller fields register after register() fields — so it can skip a Select and land on a checkbox further down. For short forms, focus the first invalid field in document order instead. Every ReactLoom control submits a named form element (Select a hidden native select, NumberInput a hidden input), so the form’s own element order works:
import type { FieldErrors, FieldValues, Path, UseFormSetFocus } from 'react-hook-form';
/** Focus the first invalid field in document order (see "Focus" above). */
export function focusFirstInvalid<T extends FieldValues>(form: HTMLFormElement, errors: FieldErrors<T>, setFocus: UseFormSetFocus<T>) {
const first = Array.from(form.elements)
.map((el) => el.getAttribute('name'))
.find((name): name is string => Boolean(name && name in errors));
if (first) setFocus(first as Path<T>);
}
// useForm({ shouldFocusError: false })
<form
noValidate
onSubmit={(event) => {
const form = event.currentTarget;
return handleSubmit(save, (errors) => focusFirstInvalid(form, errors, setFocus))(event);
}}
>For long forms, show an error summary at the top, move focus to it, and link each problem to its field — as in the example.
Server errors
Validation on the server is the source of truth. Map its response onto fields with setError(field, { message }, { shouldFocus: true }); the field shows the message and is announced through its description. For errors that belong to no field, show an Alert above the form.
Checklist
- Error messages say how to fix the problem (“Enter an email like name@company.com”), not just that it is wrong.
- Mark required fields (
requiredadds the indicator and the native attribute) and say which are optional if most are required. - Never disable the submit button to signal errors — people need to submit to find out what is wrong.
- Validate on submit first; then re-validate as people correct a field (React Hook Form’s default
reValidateMode). - Use
noValidateon the form so the browser’s own bubbles do not compete with your messages.