Form
A form that checks before sending, lists what to fix in one place, and shows it is working while it sends. The browser's own bubbles are off: every message is written next to its field.
import { Form, FormActions, Field, Input, FormProblem } from '@sypnia/ui/react'
Validation, summary and sending
Press «Create table» with the fields empty, follow a link in the summary, then fix the fields and send.
Code
import { Button, Field, Form, FormActions, FormGrid, Input, NativeSelect, Textarea, toast, Toaster, type FormProblem } from '@sypnia/ui/react';
// Press «Create table» with the name empty: the summary lists what to fix and each line takes you to its field.
// Fix the name and the error goes away at once; press again and the button works for a moment.
const check = (v: FormData): FormProblem[] => {
const problems: FormProblem[] = [];
const name = String(v.get('name') ?? '').trim();
if (!name) problems.push({ name: 'name', label: 'Name', message: 'Write a name for the table.' });
else if (!/^[a-z][a-z0-9_]*$/.test(name)) problems.push({ name: 'name', label: 'Name', message: 'Use lowercase letters, numbers and underscores, starting with a letter.' });
if (!String(v.get('rows') ?? '').trim()) problems.push({ name: 'rows', label: 'Expected rows', message: 'Write about how many rows it will hold, even a guess.' });
return problems;
};
export default function NewTable() {
return (
<>
<Form label="New table" validate={check} onSubmit={async (v) => {
await new Promise((r) => setTimeout(r, 1400));
toast(`The table ${v.get('name')} is ready`, { tone: 'ok' });
}}>
{({ errorFor }) => (
<>
<FormGrid>
<Field label="Name" hint="Lowercase, for example orders." error={errorFor('name')}><Input name="name" machine /></Field>
<Field label="Expected rows" error={errorFor('rows')}><Input name="rows" inputMode="numeric" /></Field>
<Field label="Schema"><NativeSelect name="schema" defaultValue="public"><option>public</option><option>billing</option></NativeSelect></Field>
<Field label="Description" optional wide><Textarea name="description" /></Field>
</FormGrid>
<FormActions submitLabel="Create table" busyLabel="Creating…" cancel={<Button variant="quiet">Cancel</Button>} />
</>
)}
</Form>
<Toaster />
</>
);
} Problems from the server
Press «Rename»: the server answers that the name is taken.
Code
import { useState } from 'react';
import { Field, Form, FormActions, Input, type FormProblem } from '@sypnia/ui/react';
// Some problems are only known after sending: here any name is «taken». Pass them as `problems`.
export default function ServerProblems() {
const [problems, setProblems] = useState<FormProblem[]>([]);
return (
<Form label="Rename project" problems={problems} onSubmit={async (v) => {
await new Promise((r) => setTimeout(r, 900));
setProblems([{ name: 'project', label: 'Project name', message: `${v.get('project') || 'That name'} is already used by another project in this organization. Try another one.` }]);
}}>
{({ errorFor }) => (
<>
<Field label="Project name" error={errorFor('project')}><Input name="project" defaultValue="storefront" onChange={() => setProblems([])} /></Field>
<FormActions submitLabel="Rename" busyLabel="Renaming…" align="start" />
</>
)}
</Form>
);
} Skeleton
The real piece and its skeleton: the same box, so nothing moves when the data arrives.
Code
import { Field, Form, FormActions, FormGrid, FormSkeleton, Input } from '@sypnia/ui/react';
// The form and its skeleton side by side: same boxes, so nothing moves when the values arrive.
export default function Skeleton() {
return (
<div className="sy-grid">
<Form label="Connection" onSubmit={() => {}}>
<FormGrid>
<Field label="Host"><Input name="host" machine defaultValue="db.northwind.io" /></Field>
<Field label="Port"><Input name="port" machine defaultValue="5432" /></Field>
</FormGrid>
<FormActions submitLabel="Save" />
</Form>
<FormSkeleton fields={2} columns={2} />
</div>
);
} When to use it
Use it when
- Any form that sends something: create, invite, rename, connect.
- Pass
validatefor what can be checked at once, andproblemsfor what only the server knows, such as a name already taken. - Use the function form of the children,
({ errorFor }) => …, to give each Field its message.
Do not use it when
- A single setting that saves by itself: use a Switch or an InlineEdit.
- Filters and search boxes: they change what is shown, they do not send anything.
- Checking while the person types the first time: errors appear after the first try, then clear as soon as each field is right.
For everyone
- After a failed try the focus moves to the summary, so a screen reader reads the whole list once.
- Each line of the summary is a link that moves the focus to its field.
- Fields with a problem are marked
aria-invalidand their message is tied witharia-describedby, read before the hint. - While it sends, the form is
aria-busyand the button keeps the focus and does not send twice.
Props
| Form | Type | Default |
|---|---|---|
childrenrequiredThe fields. Pass a function to get the form's state, for example `({ errorFor }) => <Field error={errorFor('name')}>…`. | ReactNode | ((state: FormState) => ReactNode) | |
onSubmitrequiredRuns on submit with the form's values. It may be async: while it runs the submit button shows it is working. | (values: FormData) => void | Promise<void> | |
className | string | |
labelAccessible name of the form, when the page has more than one. | string | |
problemsProblems found by the server after sending (for example a name already taken). | FormProblem[] | |
validateChecks the values before sending. Return the problems, or an empty list when everything is right. When there are problems nothing is sent, an ErrorSummary appears at the top and the focus moves to it. | ((values: FormData) => FormProblem[]) |
| FormActions | Type | Default |
|---|---|---|
submitLabelrequired | string | |
align | "start" | "end" | |
busyLabelWhat the submit button says while it works: «Creating…». Defaults to «Saving…». | string | |
cancelUsually a quiet Button that goes back. | ReactNode | |
danger | boolean |
| Field | Type | Default |
|---|---|---|
labelrequired | ReactNode | |
className | string | |
errorWhat is wrong and how to fix it. Its presence marks the control as invalid. | ReactNode | |
hintHelp that is always visible: what to write, in what format. | ReactNode | |
optionalAdds «optional» beside the label. Required is the default and is not marked. | boolean | |
wideSpans both columns of a FormGrid. | boolean |
| Input | Type | Default |
|---|---|---|
machineMachine text (ids, keys, code): set in the mono face. | boolean | |
size | "sm" | "md" | "lg" |