Skip to content

FormPage

A whole page that creates something: the way back, a title that says what is made, the fields in sections that each say what they are for, and one button that says what happens.

import { Form, FormSection, FormActions } from '@sypnia/ui/react'

On this page
  1. On a desktop
  2. On a phone
  3. Skeleton
  4. When the page cannot load what it needs
  5. When to use it
  6. For everyone
  7. Props

On a desktop

Press «Create database»: the name orders is already taken, so the server says so next to the field. Change it and send again.

New database

A Postgres database with its API, backups and a place in the region you choose.

Name and place

The name is part of every address of the database. The region is where the data lives, and it cannot change later.

Lowercase letters, numbers and dashes.

Choose the one closest to your users.

Size

You can change the size at any time; the database restarts for a few seconds.

Backups

Copies of the whole database, to go back to a moment before a mistake.

Cancel
Code
import { useState } from 'react';
import {
  Alert, BackButton, Button, EmptyState, Field, Form, FormActions, FormSection, Page, PageHeader,
  RadioCards, RegionSelect, Select, SkeletonOf, SlugInput, Switch, Textarea, useSypnia, type FormProblem,
} from '@sypnia/ui/react';

// A whole page that creates something: the way back, a title that says what is made, the fields in sections that each
// say what they are for, and one button that says what happens. Checks before sending, lists what to fix, and shows
// what only the server knows (a name already taken) next to its field.
const en = {
  back: 'Databases', title: 'New database', lead: 'A Postgres database with its API, backups and a place in the region you choose.',
  s1: 'Name and place', s1d: 'The name is part of every address of the database. The region is where the data lives, and it cannot change later.',
  name: 'Name', nameHint: 'Lowercase letters, numbers and dashes.', region: 'Region', regionHint: 'Choose the one closest to your users.',
  about: 'What it is for', s2: 'Size', s2d: 'You can change the size at any time; the database restarts for a few seconds.',
  s3: 'Backups', s3d: 'Copies of the whole database, to go back to a moment before a mistake.',
  daily: 'Back up every day', dailyD: 'At 03:00 in the database’s region.', keep: 'Keep copies for',
  cancel: 'Cancel', submit: 'Create database', busy: 'Creating…',
  noName: 'Write a name for the database.', taken: (n: string) => `${n} is already a database in this project. Choose another name.`, noRegion: 'Choose a region.',
  created: (n: string) => `${n} is ready`, createdBody: 'Its address and keys are on the database page. It is empty: create a table or import a CSV.',
  open: 'Open the database', another: 'Create another',
  failedTitle: 'This page could not load the regions', failedBody: 'Without them the database cannot be placed. Nothing was created. Try again.', retry: 'Try again',
  days: (n: number) => `${n} days`,
};
const es: typeof en = {
  back: 'Bases de datos', title: 'Nueva base de datos', lead: 'Una base de datos Postgres con su API, copias de seguridad y un lugar en la región que elijas.',
  s1: 'Nombre y lugar', s1d: 'El nombre va en todas las direcciones de la base de datos. La región es donde viven los datos, y no se puede cambiar después.',
  name: 'Nombre', nameHint: 'Letras minúsculas, números y guiones.', region: 'Región', regionHint: 'Elige la más cercana a tus usuarios.',
  about: 'Para qué es', s2: 'Tamaño', s2d: 'Puedes cambiar el tamaño cuando quieras; la base de datos se reinicia por unos segundos.',
  s3: 'Copias de seguridad', s3d: 'Copias de toda la base de datos, para volver a un momento antes de un error.',
  daily: 'Copiar cada día', dailyD: 'A las 03:00 en la región de la base de datos.', keep: 'Guardar las copias por',
  cancel: 'Cancelar', submit: 'Crear base de datos', busy: 'Creando…',
  noName: 'Escribe un nombre para la base de datos.', taken: (n: string) => `${n} ya es una base de datos de este proyecto. Elige otro nombre.`, noRegion: 'Elige una región.',
  created: (n: string) => `${n} está lista`, createdBody: 'Su dirección y sus llaves están en la página de la base de datos. Está vacía: crea una tabla o importa un CSV.',
  open: 'Abrir la base de datos', another: 'Crear otra',
  failedTitle: 'Esta página no pudo cargar las regiones', failedBody: 'Sin ellas no se puede ubicar la base de datos. No se creó nada. Intenta de nuevo.', retry: 'Intentar de nuevo',
  days: (n: number) => `${n} días`,
};
const regions = [
  { id: 'eu-west', name: 'Europe (Ireland)', location: 'Dublin' }, { id: 'us-east', name: 'United States (Virginia)', location: 'Ashburn' },
  { id: 'sa-east', name: 'South America (São Paulo)', location: 'São Paulo' },
];
const sizes = (es_: boolean) => [
  { value: 'small', label: es_ ? 'Pequeña' : 'Small', description: es_ ? '2 GB de memoria · hasta 10 GB de datos' : '2 GB memory · up to 10 GB of data' },
  { value: 'medium', label: es_ ? 'Mediana' : 'Medium', description: es_ ? '8 GB de memoria · hasta 100 GB de datos' : '8 GB memory · up to 100 GB of data' },
  { value: 'large', label: es_ ? 'Grande' : 'Large', description: es_ ? '32 GB de memoria · hasta 1 TB de datos' : '32 GB memory · up to 1 TB of data' },
];
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));

export default function FormPage({ state = 'ready' }: { state?: 'ready' | 'loading' | 'error' }) {
  const { locale } = useSypnia();
  const isEs = locale.startsWith('es');
  const c = isEs ? es : en;
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [daily, setDaily] = useState(true);
  const [done, setDone] = useState<string>();
  const [failed, setFailed] = useState(state === 'error');
  const header = <><div><BackButton href="#databases">{c.back}</BackButton></div><PageHeader title={c.title} lead={c.lead} /></>;
  // Loading: the real form. Only what comes from the server waits, in its own box: the regions and the sizes; the
  // rest is there, disabled until they come.
  const loading = state === 'loading';
  const off = failed || loading;
  if (done) {
    return (
      <Page>
        {header}
        <EmptyState icon="success" title={c.created(done)} actions={<><Button variant="primary" href="#database">{c.open}</Button><Button onClick={() => setDone(undefined)}>{c.another}</Button></>}>{c.createdBody}</EmptyState>
      </Page>
    );
  }
  const check = (v: FormData): FormProblem[] => {
    const out: FormProblem[] = [];
    if (!String(v.get('name') ?? '').trim()) out.push({ name: 'name', label: c.name, message: c.noName });
    if (!v.get('region')) out.push({ name: 'region', label: c.region, message: c.noRegion });
    return out;
  };
  return (
    <Page>
      {header}
      {failed && <Alert tone="fail" title={c.failedTitle} actions={<Button size="sm" icon="refresh" onClick={() => setFailed(false)}>{c.retry}</Button>}>{c.failedBody}</Alert>}
      <Form label={c.title} validate={check} problems={problems} onSubmit={async (v) => {
        await wait(1200);
        const name = String(v.get('name'));
        if (name === 'orders') setProblems([{ name: 'name', label: c.name, message: c.taken(name) }]);
        else setDone(name);
      }}>
        {({ errorFor }) => (
          <>
            <FormSection title={c.s1} description={c.s1d}>
              <Field label={c.name} hint={c.nameHint} error={errorFor('name')}><SlugInput name="name" defaultValue="orders" disabled={off} onChange={() => setProblems([])} /></Field>
              <Field label={c.region} hint={c.regionHint} error={errorFor('region')}>{loading ? <SkeletonOf><RegionSelect name="region" regions={regions} /></SkeletonOf> : <RegionSelect name="region" regions={regions} disabled={failed} />}</Field>
              <Field label={c.about} optional><Textarea name="about" rows={2} disabled={off} /></Field>
            </FormSection>
            <FormSection title={c.s2} description={c.s2d}>
              {loading ? <SkeletonOf><RadioCards name="size" aria-label={c.s2} options={sizes(isEs)} defaultValue="small" /></SkeletonOf>
                : <RadioCards name="size" aria-label={c.s2} options={sizes(isEs)} defaultValue="small" disabled={failed} />}
            </FormSection>
            <FormSection title={c.s3} description={c.s3d}>
              <Switch name="daily" label={c.daily} description={c.dailyD} checked={daily} onChange={(e) => setDaily(e.target.checked)} disabled={off} />
              {daily && <Field label={c.keep}><Select name="keep" defaultValue="30" disabled={off} options={[7, 30, 90].map((n) => ({ value: String(n), label: c.days(n) }))} /></Field>}
            </FormSection>
            <FormActions submitLabel={c.submit} busyLabel={c.busy} cancel={<Button variant="quiet" href="#databases">{c.cancel}</Button>} />
          </>
        )}
      </Form>
    </Page>
  );
}

On a phone

At 390 px each section title goes above its fields and the buttons share the width.

Skeleton

The real form while the regions and sizes load: only those two wait in their own boxes; the other fields are there, disabled.

New database

A Postgres database with its API, backups and a place in the region you choose.

Name and place

The name is part of every address of the database. The region is where the data lives, and it cannot change later.

Lowercase letters, numbers and dashes.

Choose the one closest to your users.

Size

You can change the size at any time; the database restarts for a few seconds.

Backups

Copies of the whole database, to go back to a moment before a mistake.

Cancel

When the page cannot load what it needs

The regions did not come: the form stays, disabled, under a message with «Try again».

New database

A Postgres database with its API, backups and a place in the region you choose.

Name and place

The name is part of every address of the database. The region is where the data lives, and it cannot change later.

Lowercase letters, numbers and dashes.

Choose the one closest to your users.

Size

You can change the size at any time; the database restarts for a few seconds.

Backups

Copies of the whole database, to go back to a moment before a mistake.

Cancel

When to use it

Use it when

  • Creating anything with more than a few fields: a database, a project, a webhook.
  • Sections when the fields answer different questions; each section says in one sentence why it is asked.
  • Saying in the hint what cannot change later, such as the region.

Do not use it when

  • Three fields or fewer: a Dialog is enough.
  • Editing settings that already exist: that is a SettingsPage, which saves with a SaveBar.
  • A button that says «Submit»: it says what happens, «Create database».

For everyone

  • After a failed try, the summary of what to fix takes the focus; each line moves the focus to its field.
  • Errors the server finds, like a name already taken, are tied to their field the same way.
  • Each section is a region named by its title; the page title is the only h1.

Props

FormTypeDefault
childrenrequired

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

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

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[])
FormSectionTypeDefault
titlerequired ReactNode
className string
description ReactNode
fields

How many field skeletons to show while loading.

number 2
loading

The values are on their way: the title stays and the fields are skeletons.

boolean
FormActionsTypeDefault
submitLabelrequired 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
  1. On a desktop
  2. On a phone
  3. Skeleton
  4. When the page cannot load what it needs
  5. When to use it
  6. For everyone
  7. Props

    Search pages, sections and terms