Forms
useForm & AutoForm
Form state for ReactLoom fields without a schema-library dependency: useForm wires values, errors and submission, ErrorSummary lists problems with links to them, and AutoForm renders a whole form from a list of fields.
import '@reactloom/forms/styles.css';
import { AutoForm, ErrorSummary, useForm } from '@reactloom/forms';Examples
useForm with an error summary
Submit empty to see the summary and focus moving to the first problem. Errors then update as you type.
import { ErrorSummary, useForm } from '@reactloom/forms';
import { Button, Checkbox, Input, Stack, Text } from '@reactloom/ui';
import { useState } from 'react';
interface SignUp {
[key: string]: unknown;
name: string;
email: string;
terms: boolean;
}
export default function Example() {
const [done, setDone] = useState('');
const form = useForm<SignUp>({
defaultValues: { name: '', email: '', terms: false },
validate: (v) => ({ email: v.email && !/^\S+@\S+\.\S+$/.test(v.email) ? 'Enter an email address like name@example.com' : undefined }),
onSubmit: async (values, { setErrors }) => {
await new Promise((r) => setTimeout(r, 700));
// A server error is shown on its field, which gets focus.
if (values.email.endsWith('@taken.dev')) return setErrors({ email: 'This email address is already registered' });
setDone(`Welcome, ${values.name}!`);
},
});
return (
<form {...form.getFormProps()} aria-label="Sign up" style={{ width: '100%', maxWidth: 420 }}>
<Stack gap="4">
{form.submitCount > 0 && <ErrorSummary errors={form.errorList} />}
<Input label="Name" autoComplete="name" {...form.register('name', { required: true, label: 'Name' })} />
<Input label="Email" type="email" autoComplete="email" description="Try someone@taken.dev" {...form.register('email', { required: true, label: 'Email' })} />
<Checkbox label="I accept the terms" {...form.register('terms', { required: true, label: 'Terms', as: 'checkbox' })} />
<div>
<Button type="submit" loading={form.isSubmitting}>
Create account
</Button>
</div>
{done && <Text role="status">{done}</Text>}
</Stack>
</form>
);
}AutoForm with a conditional field
“Phone number” appears only when Phone is chosen; hidden fields are neither validated nor submitted.
import { AutoForm, type AutoField } from '@reactloom/forms';
import { useState } from 'react';
interface Contact {
[key: string]: unknown;
name: string;
method: string | null;
phone: string;
topic: string | null;
message: string;
newsletter: boolean;
}
const fields: AutoField<Contact>[] = [
{ name: 'name', label: 'Name', required: true, autoComplete: 'name' },
{
name: 'method',
label: 'Contact me by',
type: 'radio',
required: true,
options: [
{ value: 'email', label: 'Email' },
{ value: 'phone', label: 'Phone' },
],
},
// Only shown (and validated) when “Phone” is chosen.
{ name: 'phone', label: 'Phone number', type: 'tel', required: true, autoComplete: 'tel', when: (v) => v.method === 'phone' },
{
name: 'topic',
label: 'Topic',
type: 'select',
placeholder: 'Choose a topic',
options: [
{ value: 'billing', label: 'Billing' },
{ value: 'support', label: 'Support' },
],
},
{ name: 'message', label: 'Message', type: 'textarea', required: true, validate: (v) => (String(v).length < 10 ? 'Write at least 10 characters' : undefined) },
{ name: 'newsletter', label: 'Send me the newsletter', type: 'switch' },
];
export default function Example() {
const [sent, setSent] = useState<string>();
return (
<div style={{ width: '100%', maxWidth: 420 }}>
<AutoForm aria-label="Contact us" fields={fields} submitLabel="Send" onSubmit={(values) => setSent(JSON.stringify(values, null, 2))} />
{sent && <pre aria-label="Submitted values">{sent}</pre>}
</div>
);
}API reference
| Prop | Type | Default |
|---|---|---|
defaultValuesrequiredInitial values; also the shape of the form. | object | — |
onSubmitrequiredCalled with valid values; isSubmitting is true while it runs. | (values, { setErrors, reset }) => void | Promise | — |
validateErrors by field. Plug Zod or Valibot in here. | (values) => { [field]: message } | — |
focusOnErrorFocus the first invalid field after a failed submit. | boolean | true |
messages.requiredError for empty required fields. | string | 'This field is required.' |
| Prop | Type | Default |
|---|---|---|
register(name, { required?, label?, as? })id, name, value / checked, onChange / onCheckedChange / onValueChange, onBlur, error, invalid, required. as: 'input' (default), 'checkbox' or 'value'; label names the field in ErrorSummary. | field props | — |
values · errors · touchedCurrent state. | objects | — |
isSubmitting · submitCountSubmission state. | boolean · number | — |
errorListShown errors in field order, for ErrorSummary. | { name, id, message }[] | — |
getFormProps() · handleSubmitWire the form element. | form props · (event?) => Promise | — |
setValue · setErrors · reset · focusFieldImperative helpers. | functions | — |
| Prop | Type | Default |
|---|---|---|
AutoForm fieldsrequiredtext, email, password, number, tel, url, date, textarea, select, radio, checkbox, switch. | { name, label, type?, required?, options?, when?, validate?, … }[] | — |
AutoForm defaultValues · validate · onSubmitAs for useForm; onSubmit gets only visible fields. | — | — |
AutoForm renderFieldReplace any field. | (field, form) => ReactNode | undefined | — |
AutoForm submitLabel · actions · errorSummaryFooter and summary. | ReactNode · ReactNode · boolean | 'Submit' · — · true |
ErrorSummary errors · titleThe list and its heading. | FormErrorEntry[] · ReactNode | (n) => ReactNode | — |
Customization
Extracted from the component’s source on every build, so it matches the code. How the layers fit together is explained in Customization.
AutoForm
Slot class names
Add classes to inner parts with classNames (className is shorthand for root): root, summary, fields, actions, submit.
CSS variables
| Variable | Default |
|---|---|
--pl-form-field-gap | var(--pl-space-4) |
--pl-form-gap | var(--pl-space-5) |
ErrorSummary
Slot class names
Add classes to inner parts with classNames (className is shorthand for root): root, title, list, item, link.
Theme tokens it reads
--pl-color-danger-border --pl-color-danger-fg --pl-color-danger-subtle --pl-focus-ring-color --pl-focus-ring-width --pl-radius-md
Accessibility
- Errors appear after a field is left or the form is submitted, never while typing a first attempt; once shown, they clear as soon as the value is fixed.
- A failed submit focuses the first invalid field. ErrorSummary is an alert whose links move focus to each field.
- Every control keeps its visible label, and errors are linked with
aria-describedby.
| Key | Action |
|---|---|
| Tab | Move between fields and the summary links |
| Enter | Submit (in a text field), or follow a summary link to its field |
| Space | Toggle a checkbox or switch |
Usage guidelines
Do
- Keep the summary above the form and the messages specific (“Enter an email address like name@example.com”).
Don’t
- Don’t disable the submit button to signal errors; let people submit and show what to fix.