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, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/en/components/form.md.

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.

Used for project notifications
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>
  );
}

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.

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>
  );
}

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.

.account-form {
  --app-form-label-width: 140px;
}
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.

Save changes automatically while editing.
Introduce yourself to other members.
Up to 120 characters.
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>
  );
}

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.

<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.

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.

Contacts
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>
  );
}

Error summary

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

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>
  );
}

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.

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>
  );
}

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.

npm install react-hook-form
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.

PropertyTypeDefaultDescription
layout'horizontal' | 'vertical' | 'settings''horizontal'Default field layout; settings places labels and descriptions on the left and controls in a right-side control column.
labelWidthnumber | string112Label-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.
settingsControlWidthnumber | 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().
disabledbooleanfalseDisable interaction.
refRef<HTMLFormElement>—Reference to the form

FormField API

Props associating a field label, control and validation messages.

PropertyTypeDefaultDescription
labelReactNode—Field label
htmlForstringGeneratedThe associated control ID; one field wraps one control or group
requiredbooleanfalseRequire a non-empty value; compound controls validate once.
helpReactNode—Supporting text below the control, included in the field layout
errorReactNode—Error message, displayed instead of help
layoutFormProps['layout']Inherited from FormOverride this field's layout; vertical allows wider controls to fill the row
labelWidthnumber | string—Override this horizontal/settings field’s label-column width; numbers use pixels and strings accept CSS lengths, percentages, or functions such as clamp()
controlAlignFormProps['controlAlign']Inherited from FormOverride control alignment for this settings field.
settingsControlWidthFormProps['settingsControlWidth']Inherited from FormOverride the fixed control-column width for this settings field; when omitted, the remaining width after the label column and gap is used.
descriptionReactNode—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.

PropertyTypeDefaultDescription
legendReactNode—Field group title
descriptionReactNode—Supporting description

FormListProps API

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

PropertyTypeDefaultDescription
namestringRequiredField-name prefix; use field.name on the actual control. Dotted names do not construct nested objects.
valuereadonly T[]—Controlled value
defaultValuereadonly 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<T>[], operations: FormListOperations<T>) => ReactNodeRequiredRender function for fields and row operations.

FormListField API

Information for one field passed to the list rendering function.

PropertyTypeDefaultDescription
keystringRequiredUnique stable identifier
indexnumberRequiredCurrent index, starting at zero
namestringRequiredForm field name
valueTRequiredCurrent value of this row.

FormListOperations API

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

PropertyTypeDefaultDescription
add(value: T, index?: number) => voidRequiredInsert a field; omitted index appends
remove(index: number | readonly number[]) => voidRequiredRemove one or multiple indices
move(from: number, to: number) => voidRequiredMove fields preserving stable keys
update(index: number, value: T) => voidRequiredUpdate field value

FormErrorSummaryProps API

Props for presenting field validation errors together.

PropertyTypeDefaultDescription
errorsreadonly FormError[]—Omitted collects field errors in this Form
titleReactNodeLocalized defaultError-summary heading, localized by default.

FormError API

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

PropertyTypeDefaultDescription
fieldIdstringRequiredInput id focused when error is clicked
messageReactNodeRequiredError content
labelReactNode—Display label

FormValidationApi

State and form event handlers returned by useFormValidation.

PropertyTypeDefaultDescription
errorsRecord<string, string>RequiredField-keyed errors for FormField.
pendingbooleanRequiredWhether validation or submission is pending.
setErrorsDispatch<SetStateAction<Record<string, string>>>RequiredSet server or business errors.
handleSubmit(event: FormEvent<HTMLFormElement>) => Promise<void>RequiredBind to Form.onSubmit.
handleReset(event: FormEvent<HTMLFormElement>) => voidRequiredBind to Form.onReset to cancel requests and clear errors.
cancel() => voidRequiredCancel the current request.
clearErrors(name?: string) => voidRequiredClear one or all errors and cancel stale requests.

FormValidationOptions

Configuration for application validation, submission callbacks and error handling.

PropertyTypeDefaultDescription
validate( data: FormData, signal: AbortSignal, ) => Record<string, string> | Promise<Record<string, string>>RequiredValidate 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.
focusErrorbooleantrueFocus the first invalid field.