Ir al contenido

Form

Un formulario que revisa antes de enviar, reúne en un solo lugar lo que hay que corregir y muestra que está trabajando mientras envía. Las burbujas propias del navegador están apagadas: cada mensaje va escrito junto a su campo.

import { Form, FormActions, Field, Input, FormProblem } from '@sypnia/ui/react'

En esta página
  1. Validación, resumen y envío
  2. Problemas que vienen del servidor
  3. Skeleton
  4. Cuándo usarlo
  5. Para todos
  6. Props

Validación, resumen y envío

Pulsa «Create table» con los campos vacíos, sigue un enlace del resumen, corrige los campos y envía.

Lowercase, for example orders.

Código
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 />
    </>
  );
}

Problemas que vienen del servidor

Pulsa «Rename»: el servidor responde que el nombre ya existe.

Código
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

La pieza real y su skeleton: la misma caja, así nada se mueve cuando llegan los datos.

Código
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>
  );
}

Cuándo usarlo

Úsalo cuando

  • Cualquier formulario que envía algo: crear, invitar, renombrar, conectar.
  • Pasa validate para lo que se puede revisar al instante, y problems para lo que solo sabe el servidor, como un nombre que ya existe.
  • Usa los hijos como función, ({ errorFor }) => …, para darle a cada Field su mensaje.

No lo uses cuando

  • Un solo ajuste que se guarda solo: usa un Switch o un InlineEdit.
  • Filtros y buscadores: cambian lo que se ve, no envían nada.
  • Revisar mientras la persona escribe por primera vez: los errores aparecen tras el primer intento y se quitan en cuanto cada campo queda bien.

Para todos

  • Tras un intento fallido el foco pasa al resumen, así un lector de pantalla lee la lista completa una vez.
  • Cada línea del resumen es un enlace que lleva el foco a su campo.
  • Los campos con un problema quedan marcados con aria-invalid y su mensaje se une con aria-describedby, y se lee antes que la ayuda.
  • Mientras envía, el formulario está aria-busy y el botón conserva el foco y no envía dos veces.

Props

FormTipoPor defecto
childrenobligatorio

The fields. Pass a function to get the form's state, for example `({ errorFor }) => <Field error={errorFor('name')}>…`.

ReactNode | ((state: FormState) => ReactNode)
onSubmitobligatorio

Runs 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
label

Accessible name of the form, when the page has more than one.

string
problems

Problems found by the server after sending (for example a name already taken).

FormProblem[]
validate

Checks 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[])
FormActionsTipoPor defecto
submitLabelobligatorio string
align "start" | "end"
busyLabel

What the submit button says while it works: «Creating…». Defaults to «Saving…».

string
cancel

Usually a quiet Button that goes back.

ReactNode
danger boolean
FieldTipoPor defecto
labelobligatorio ReactNode
className string
error

What is wrong and how to fix it. Its presence marks the control as invalid.

ReactNode
hint

Help that is always visible: what to write, in what format.

ReactNode
optional

Adds «optional» beside the label. Required is the default and is not marked.

boolean
wide

Spans both columns of a FormGrid.

boolean
InputTipoPor defecto
machine

Machine text (ids, keys, code): set in the mono face.

boolean
size "sm" | "md" | "lg"
  1. Validación, resumen y envío
  2. Problemas que vienen del servidor
  3. Skeleton
  4. Cuándo usarlo
  5. Para todos
  6. Props

    Busca páginas, secciones y términos