Skip to content

Form

A form whose fields show their validation errors. onSubmit receives the FormData of the named fields instead of the browser submitting the form. It can return errors keyed by field name, also from a promise, which show on those fields until they are edited.

Type
Form.tsx
import {
  Button,
  Form,
  Select,
  SelectItem,
  Stack,
  Text,
  TextField
} from 'alinea/components'
import {useState} from 'react'

// Stands in for a request to your own API, which returns errors by field name
async function createPage(data: FormData) {
  await new Promise(resolve => setTimeout(resolve, 300))
  if (data.get('path') === 'about') return {path: 'This path is taken'}
  return undefined
}

export function FormExample() {
  const [created, setCreated] = useState<string>()
  return (
    <Form
      style={{width: 300}}
      onSubmit={async data => {
        const errors = await createPage(data)
        if (!errors) setCreated(String(data.get('title')))
        return errors
      }}
    >
      <Stack gap={16}>
        <TextField label="Title" name="title" required />
        <TextField label="Path" name="path" defaultValue="about" />
        <Select label="Type" name="type" defaultValue="page">
          <SelectItem value="page">Page</SelectItem>
          <SelectItem value="post">Blog post</SelectItem>
        </Select>
        <Button type="submit" color="primary">
          Create page
        </Button>
        {created && <Text size="sm">Created “{created}”</Text>}
      </Stack>
    </Form>
  )
}

Validation

Native constraints are checked when the form is submitted: required, and pattern, minLength and maxLength on a TextField. validationErrors shows errors you already have, for example from a server, keyed by field name like the ones onSubmit returns. An error set on a field itself takes precedence.

The form controls of alinea/components take a name to be submitted under: text, number and select controls submit their value as a string, dates and times as ISO strings (2026-09-23, 14:30) and MultipleSelect one entry per picked value. To submit a form from a dialog, pass onSubmit to DialogContent: the dialog closes once it succeeds.

Props

A form whose fields show validation errors: native constraints such as required once the form is submitted, and validationErrors or the errors returned by onSubmit by field name. An error set on a field itself takes precedence.

PropTypeDefaultDescription
validationErrorsValidationErrorsDefault –Errors keyed by field name, eg. from the server. A field shows its error until it is edited.
onSubmit(data: FormData) => FormSubmitResult | Promise<FormSubmitResult>Default –Called with the form data instead of submitting the form natively. Errors it returns are shown on the fields, next to validationErrors.

Also accepts className and style, id and aria-* labelling attributes and data-* attributes.