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.

Preview

Try someone@taken.dev

Example.tsx
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.

Preview
Contact me by
Topic
Example.tsx
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

useForm(options)
PropTypeDefault
defaultValuesrequired
Initial values; also the shape of the form.
object—
onSubmitrequired
Called with valid values; isSubmitting is true while it runs.
(values, { setErrors, reset }) => void | Promise—
validate
Errors by field. Plug Zod or Valibot in here.
(values) => { [field]: message }—
focusOnError
Focus the first invalid field after a failed submit.
booleantrue
messages.required
Error for empty required fields.
string'This field is required.'
useForm() returns
PropTypeDefault
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 · touched
Current state.
objects—
isSubmitting · submitCount
Submission state.
boolean · number—
errorList
Shown errors in field order, for ErrorSummary.
{ name, id, message }[]—
getFormProps() · handleSubmit
Wire the form element.
form props · (event?) => Promise—
setValue · setErrors · reset · focusField
Imperative helpers.
functions—
AutoForm and ErrorSummary
PropTypeDefault
AutoForm fieldsrequired
text, email, password, number, tel, url, date, textarea, select, radio, checkbox, switch.
{ name, label, type?, required?, options?, when?, validate?, … }[]—
AutoForm defaultValues · validate · onSubmit
As for useForm; onSubmit gets only visible fields.
——
AutoForm renderField
Replace any field.
(field, form) => ReactNode | undefined—
AutoForm submitLabel · actions · errorSummary
Footer and summary.
ReactNode · ReactNode · boolean'Submit' · — · true
ErrorSummary errors · title
The 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

VariableDefault
--pl-form-field-gapvar(--pl-space-4)
--pl-form-gapvar(--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.
Keyboard interactions
KeyAction
TabMove between fields and the summary links
EnterSubmit (in a text field), or follow a summary link to its field
SpaceToggle 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.