> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/en/components/form.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/en/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/en/llms-full.txt.

# Form

Organize fields, labels and validation feedback, and collect form data.


## Basic usage

Set a control’s `name` and read its value from `FormData` in the submit event. `FormField required` and input types enable native validation, with errors shown below the corresponding fields.


*Name

*Work email

Used for project notifications

*Team

SubmitReset

basic.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/basic.tsx"
import { Button, Flex, Form, FormField, Input, Select, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function FormBasic() {
  const [result, setResult] = useState('');
  return (
    <Form
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        setResult(`${data.get('name')} · ${data.get('email')} · ${data.get('team')}`);
      }}
      onReset={() => setResult('')}
    >
      <FormField label="Name" required>
        <Input name="name" placeholder="Your name" />
      </FormField>
      <FormField label="Work email" required help="Used for project notifications">
        <Input name="email" type="email" placeholder="hello@example.com" />
      </FormField>
      <FormField label="Team" required>
        <Select
          name="team"
          options={[
            { value: 'design', label: 'Design team' },
            { value: 'engineering', label: 'Engineering team' },
          ]}
        />
      </FormField>
      <FormField>
        <Flex gap="sm" wrap>
          <Button type="submit" variant="solid">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </Flex>
      </FormField>
      {result && (
        <FormField>
          <Text role="status" tone="muted">
            Submitted: {result}
          </Text>
        </FormField>
      )}
    </Form>
  );
}
```

Expand code


## Examples

### Label widths

Horizontal and settings label columns default to 112px. Set `Form.labelWidth` for the whole form or `FormField.labelWidth` for an individual field; numbers use pixels and strings accept CSS values such as `20%`, `12rem`, or `clamp()`. Long labels wrap within that width. Horizontal and settings fields stack in narrow containers.


Name

Work email

Notes

label-width.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/label-width.tsx"
import { Form, FormField, Input } from '@ifhover/leaf-ui';

export function FormLabelWidth() {
  return (
    <Form labelWidth={140}>
      <FormField label="Name">
        <Input name="name" />
      </FormField>
      <FormField label="Work email">
        <Input name="email" />
      </FormField>
      <FormField label="Notes" labelWidth={80}>
        <Input name="notes" />
      </FormField>
    </Form>
  );
}
```

Expand code

### Label widths through CSS


When using build tools such as `postcss-pxtorem`, define the width in a stylesheet so your CSS pipeline can convert its unit. You can also use `rem` directly. The following example connects the label width to an application CSS variable through `style`.

```css
.account-form {
  --app-form-label-width: 140px;
}
```

```tsx
import { Form, FormField, Input, type LeafThemeStyle } from '@ifhover/leaf-ui';
import './account-form.css';

const formStyle = {
  '--leaf-form-label-width': 'var(--app-form-label-width)',
} satisfies LeafThemeStyle;

export function AccountForm() {
  return (
    <Form className="account-form" style={formStyle}>
      <FormField label="Account name">
        <Input name="account" />
      </FormField>
    </Form>
  );
}
```

Whether `140px` is converted, and at what ratio, depends on your build configuration. Include this stylesheet and its custom property declarations in the conversion scope. Numeric `labelWidth` values generate inline pixel values, which PostCSS usually does not process; string values are passed through as CSS widths. Form currently also generates an inline default width, so declaring `--leaf-form-label-width` in a CSS class on the same Form does not override it. The example explicitly connects the CSS variable through `style` without requiring `!important`.

For an application-wide width, define `--app-form-label-width` on the application root and configure `ConfigProvider components={{ Form: { style: formStyle } }}` once. `style` is replaced as a whole, not merged; retain the variable connection when supplying a separate `style` on a Form. `FormField.labelWidth` or the same CSS variable on an individual field can still override that field.

### Settings layout

`layout="settings"` places the label and `description` to the left of the controls. The left column reads `labelWidth`; controls use the remaining width after the gap and align left by default. Set `controlAlign="right"` on Form or override an individual FormField. Use `layout="vertical"` for wider fields; it still fills the row by default. `description` explains the field; `help` appears below the control and is replaced by `error`.


Language

Auto-save

Save changes automatically while editing.

Biography

Introduce yourself to other members.

Up to 120 characters.

settings.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/settings.tsx"
import { Form, FormField, Select, Switch, Textarea } from '@ifhover/leaf-ui';

export function FormSettings() {
  return (
    <Form layout="settings">
      <FormField label="Language">
        <Select
          name="language"
          defaultValue="zh-CN"
          options={[
            { value: 'zh-CN', label: 'Simplified Chinese' },
            { value: 'en-US', label: 'English' },
          ]}
        />
      </FormField>
      <FormField label="Auto-save" description="Save changes automatically while editing.">
        <Switch name="autoSave" defaultChecked />
      </FormField>
      <FormField
        label="Biography"
        description="Introduce yourself to other members."
        layout="vertical"
        help="Up to 120 characters."
      >
        <Textarea name="biography" rows={3} maxLength={120} />
      </FormField>
    </Form>
  );
}
```

Expand code

### Settings control-column width


The control column uses the space left after the label column and column gap. To keep a fixed control column for compatibility, set `settingsControlWidth`; numbers use pixels and strings accept CSS values such as `rem`, percentages, or `clamp()`. Fields stack vertically when the Form or viewport becomes narrow.

Use `settingsControlWidth` only when a fixed control column is needed. FormField can override one field, and ConfigProvider can set an application or region default.

```tsx
<Form layout="settings" settingsControlWidth={240}>
  <FormField label="Language">...</FormField>
  <FormField label="Auto-save" settingsControlWidth="18rem">...</FormField>
</Form>

<ConfigProvider components={{ Form: { settingsControlWidth: 'clamp(220px, 36%, 300px)' } }}>
  <App />
</ConfigProvider>
```

To connect an application CSS variable, override the component variable directly. A value supplied through `style` takes precedence over `settingsControlWidth`.

```tsx
import { Form, type LeafThemeStyle } from '@ifhover/leaf-ui';

const formStyle = {
  '--leaf-form-settings-control-width': 'var(--app-settings-control-width)',
} satisfies LeafThemeStyle;

<Form layout="settings" style={formStyle}>
  ...
</Form>;
```

### Dynamic form lists

`FormList` manages row values, insertion, removal and ordering. Use `field.key` as the React key and pass `field.name` to the actual control. Moving a row updates its index and name. An uncontrolled list restores `defaultValue` on form reset.

`name` is only a field-name prefix. Dotted names remain literal strings in `FormData`; they do not create nested objects.


ContactsContact 1

RemoveMove up

Add contactReset

extensions.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/extensions.tsx"
import { Button, Flex, Form, FormField, FormGroup, FormList, Input } from '@ifhover/leaf-ui';

export function ExtensionDemo() {
  return (
    <Form onSubmit={(event) => event.preventDefault()}>
      <FormGroup legend="Contacts">
        <FormList name="contacts" defaultValue={['']}>
          {(fields, operations) => (
            <>
              {fields.map((field) => (
                <FormField key={field.key} label={`Contact ${field.index + 1}`}>
                  <Flex direction="column" gap="sm">
                    <Input
                      name={field.name}
                      type="email"
                      placeholder="hello@example.com"
                      value={field.value}
                      onChange={(event) => operations.update(field.index, event.target.value)}
                    />
                    <Flex gap="sm" wrap>
                      <Button onClick={() => operations.remove(field.index)}>Remove</Button>
                      <Button
                        disabled={field.index === 0}
                        onClick={() => operations.move(field.index, field.index - 1)}
                      >
                        Move up
                      </Button>
                    </Flex>
                  </Flex>
                </FormField>
              ))}
              <FormField>
                <Flex gap="sm" wrap>
                  <Button onClick={() => operations.add('')}>Add contact</Button>
                  <Button type="reset" variant="outline">
                    Reset
                  </Button>
                </Flex>
              </FormField>
            </>
          )}
        </FormList>
      </FormGroup>
    </Form>
  );
}
```

Expand code

### Error summary

Place `FormErrorSummary` inside the same `Form` to collect field errors. Submit the empty form, then select an error to focus its control.


*Name

*Email

ValidateReset

error-summary.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/error-summary.tsx"
import { Button, Flex, Form, FormErrorSummary, FormField, Input } from '@ifhover/leaf-ui';

export function FormSummary() {
  return (
    <Form onSubmit={(event) => event.preventDefault()}>
      <FormErrorSummary />
      <FormField label="Name" required>
        <Input name="name" />
      </FormField>
      <FormField label="Email" required>
        <Input name="email" type="email" />
      </FormField>
      <FormField>
        <Flex gap="sm" wrap>
          <Button type="submit" variant="solid">
            Validate
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </Flex>
      </FormField>
    </Form>
  );
}
```

Expand code

### Custom validation

`useFormValidation` reads `FormData` and manages errors and `pending`. Use `noValidate` to take over validation and pass field-keyed errors to `FormField`. This example validates synchronously and clears the field error on input.


*Name

SaveReset

validation.tsx

Copy code

```tsx lineNumbers file="../../../src/examples/en/form/validation.tsx"
import { Button, Flex, Form, FormField, Input, Text, useFormValidation } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function FormValidation() {
  const [saved, setSaved] = useState('');
  const validation = useFormValidation({
    validate: (data) => {
      const errors: Record<string, string> = {};
      if (!String(data.get('name') ?? '').trim()) errors.name = 'Enter a name';
      return errors;
    },
    onSubmit: (data) => setSaved(String(data.get('name')).trim()),
  });
  return (
    <Form
      noValidate
      onSubmit={validation.handleSubmit}
      onReset={(event) => {
        validation.handleReset(event);
        setSaved('');
      }}
    >
      <FormField label="Name" required error={validation.errors.name}>
        <Input
          name="name"
          onChange={() => {
            validation.clearErrors('name');
            setSaved('');
          }}
        />
      </FormField>
      <FormField>
        <Flex gap="sm" wrap>
          <Button type="submit" loading={validation.pending}>
            Save
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </Flex>
      </FormField>
      {saved && (
        <FormField>
          <Text role="status" tone="muted">
            Saved: {saved}
          </Text>
        </FormField>
      )}
    </Form>
  );
}
```

Expand code

Asynchronous `validate` and `onSubmit` callbacks must honor the provided `AbortSignal`. A new submission cancels the previous request; `clearErrors` also cancels the current request. Bind `handleReset` to the form reset event to cancel requests and clear errors.

### React Hook Form integration


This third-party integration is a code-only example: the documentation site does not load React Hook Form. Install it in your application first. Use `register` for native inputs and `Controller` for value-based controls.

```bash
npm install react-hook-form
```

```tsx
import { Button, Form, FormField, Input, Select } from '@ifhover/leaf-ui';
import { Controller, useForm } from 'react-hook-form';

export function AccountForm() {
  const { register, control, handleSubmit, formState: { errors } } = useForm({
    defaultValues: { email: '', role: '' },
  });
  return (
    <Form noValidate onSubmit={handleSubmit((values) => console.log(values))}>
      <FormField label="Email" error={errors.email?.message}>
        <Input {...register('email', { required: 'Enter an email' })} />
      </FormField>
      <Controller
        name="role"
        control={control}
        rules={{ required: 'Choose a role' }}
        render={({ field, fieldState }) => (
          <FormField label="Role" error={fieldState.error?.message}>
            <Select {...field} options={[{ value: 'editor', label: 'Editor' }]} />
          </FormField>
        )}
      />
      <Button type="submit">Save</Button>
    </Form>
  );
}
```

Use React Hook Form’s `useFieldArray` for arrays.


## API

### Form API

#### Form integration

`FormData` values are strings or `File` objects. Convert numbers and assemble objects in your application. Unchecked checkboxes do not submit `false`; use `getAll()` for repeated names. Native reset restores uncontrolled defaults; reset controlled state in your application.

Leaf UI controls read the associations supplied by `FormField`. For native or third-party controls, provide matching `id` and `htmlFor` values. `Form disabled` passes disabled state to controls that consume its context; it does not disable arbitrary DOM elements or prevent submission.

| Property               | Type                                       | Default        | Description                                                                                                                                                                                                               |
| ---------------------- | ------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layout`               | `'horizontal' \| 'vertical' \| 'settings'` | `'horizontal'` | Default field layout; settings places labels and descriptions on the left and controls in a right-side control column.                                                                                                    |
| `labelWidth`           | `number \| string`                         | `112`          | Label-column width for horizontal/settings fields; numbers use pixels and strings accept CSS lengths, percentages, or functions such as clamp(). FormField.labelWidth can override individual fields.                     |
| `labelAlign`           | `'left' \| 'right'`                        | `'right'`      | Label alignment for horizontal fields                                                                                                                                                                                     |
| `controlAlign`         | `'left' \| 'right'`                        | `'left'`       | Control alignment within the control column of settings fields.                                                                                                                                                           |
| `settingsControlWidth` | `number \| string`                         | —              | Optional fixed control-column width for settings; when omitted, the remaining width after the label column and gap is used. Numbers use pixels and strings accept CSS lengths, percentages, or functions such as clamp(). |
| `disabled`             | `boolean`                                  | `false`        | Disable interaction.                                                                                                                                                                                                      |
| `ref`                  | `Ref<HTMLFormElement>`                     | —              | Reference to the form                                                                                                                                                                                                     |

### FormField API

Props associating a field label, control and validation messages.

| Property               | Type                                               | Default             | Description                                                                                                                                                |
| ---------------------- | -------------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label`                | `ReactNode`                                        | —                   | Field label                                                                                                                                                |
| `htmlFor`              | `string`                                           | Generated           | The associated control ID; one field wraps one control or group                                                                                            |
| `required`             | `boolean`                                          | `false`             | Require a non-empty value; compound controls validate once.                                                                                                |
| `help`                 | `ReactNode`                                        | —                   | Supporting text below the control, included in the field layout                                                                                            |
| `error`                | `ReactNode`                                        | —                   | Error message, displayed instead of help                                                                                                                   |
| `layout`               | [`FormProps`](#form-api)`['layout']`               | Inherited from Form | Override this field's layout; vertical allows wider controls to fill the row                                                                               |
| `labelWidth`           | `number \| string`                                 | —                   | Override this horizontal/settings field’s label-column width; numbers use pixels and strings accept CSS lengths, percentages, or functions such as clamp() |
| `controlAlign`         | [`FormProps`](#form-api)`['controlAlign']`         | Inherited from Form | Override control alignment for this settings field.                                                                                                        |
| `settingsControlWidth` | [`FormProps`](#form-api)`['settingsControlWidth']` | Inherited from Form | Override the fixed control-column width for this settings field; when omitted, the remaining width after the label column and gap is used.                 |
| `description`          | `ReactNode`                                        | —                   | Description below the label, displayed independently of help and error below the control                                                                   |

### FormGroupProps API

Props for the legend and description of a form field group.

| Property      | Type        | Default | Description            |
| ------------- | ----------- | ------- | ---------------------- |
| `legend`      | `ReactNode` | —       | Field group title      |
| `description` | `ReactNode` | —       | Supporting description |

### FormListProps API

Props for the data, field naming and rendering of a dynamic form list.

| Property       | Type                                                                                                                                             | Default  | Description                                                                                            |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------ |
| `name`         | `string`                                                                                                                                         | Required | Field-name prefix; use field.name on the actual control. Dotted names do not construct nested objects. |
| `value`        | `readonly T[]`                                                                                                                                   | —        | Controlled value                                                                                       |
| `defaultValue` | `readonly T[]`                                                                                                                                   | `[]`     | Initial value, restored by uncontrolled form resets                                                    |
| `onChange`     | `(values: T[]) => void`                                                                                                                          | —        | Value change callback                                                                                  |
| `itemKey`      | `(value: T) => string`                                                                                                                           | —        | Return a stable identifier                                                                             |
| `children`     | `(fields: readonly `[`FormListField`](#formlistfield-api)`<T>[], operations: `[`FormListOperations`](#formlistoperations-api)`<T>) => ReactNode` | Required | Render function for fields and row operations.                                                         |

### FormListField API

Information for one field passed to the list rendering function.

| Property | Type     | Default  | Description                     |
| -------- | -------- | -------- | ------------------------------- |
| `key`    | `string` | Required | Unique stable identifier        |
| `index`  | `number` | Required | Current index, starting at zero |
| `name`   | `string` | Required | Form field name                 |
| `value`  | `T`      | Required | Current value of this row.      |

### FormListOperations API

Methods for inserting, removing, moving and updating dynamic form list entries.

| Property | Type                                           | Default  | Description                           |
| -------- | ---------------------------------------------- | -------- | ------------------------------------- |
| `add`    | `(value: T, index?: number) => void`           | Required | Insert a field; omitted index appends |
| `remove` | `(index: number \| readonly number[]) => void` | Required | Remove one or multiple indices        |
| `move`   | `(from: number, to: number) => void`           | Required | Move fields preserving stable keys    |
| `update` | `(index: number, value: T) => void`            | Required | Update field value                    |

### FormErrorSummaryProps API

Props for presenting field validation errors together.

| Property | Type                                         | Default           | Description                                  |
| -------- | -------------------------------------------- | ----------------- | -------------------------------------------- |
| `errors` | `readonly `[`FormError`](#formerror-api)`[]` | —                 | Omitted collects field errors in this Form   |
| `title`  | `ReactNode`                                  | Localized default | Error-summary heading, localized by default. |

### FormError API

The field identity, label and message of an error summary entry.

| Property  | Type        | Default  | Description                            |
| --------- | ----------- | -------- | -------------------------------------- |
| `fieldId` | `string`    | Required | Input id focused when error is clicked |
| `message` | `ReactNode` | Required | Error content                          |
| `label`   | `ReactNode` | —        | Display label                          |

### FormValidationApi

State and form event handlers returned by `useFormValidation`.

| Property       | Type                                                   | Default  | Description                                               |
| -------------- | ------------------------------------------------------ | -------- | --------------------------------------------------------- |
| `errors`       | `Record<string, string>`                               | Required | Field-keyed errors for FormField.                         |
| `pending`      | `boolean`                                              | Required | Whether validation or submission is pending.              |
| `setErrors`    | `Dispatch<SetStateAction<Record<string, string>>>`     | Required | Set server or business errors.                            |
| `handleSubmit` | `(event: FormEvent<HTMLFormElement>) => Promise<void>` | Required | Bind to Form.onSubmit.                                    |
| `handleReset`  | `(event: FormEvent<HTMLFormElement>) => void`          | Required | Bind to Form.onReset to cancel requests and clear errors. |
| `cancel`       | `() => void`                                           | Required | Cancel the current request.                               |
| `clearErrors`  | `(name?: string) => void`                              | Required | Clear one or all errors and cancel stale requests.        |

### FormValidationOptions

Configuration for application validation, submission callbacks and error handling.

| Property     | Type                                                                                                    | Default  | Description                                                              |
| ------------ | ------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------ |
| `validate`   | `( data: FormData, signal: AbortSignal, ) => Record<string, string> \| Promise<Record<string, string>>` | Required | Validate FormData with a cancellation signal; return field-keyed errors. |
| `onSubmit`   | `(data: FormData, signal: AbortSignal) => void \| Promise<void>`                                        | —        | Submit after validation, respecting cancellation.                        |
| `onError`    | `(error: unknown) => void`                                                                              | —        | Called when validation or submission throws.                             |
| `focusError` | `boolean`                                                                                               | `true`   | Focus the first invalid field.                                           |
