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.
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.
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.
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>;
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.
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.
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.
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.
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
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.
Props associating a field label, control and validation messages.
Props for the legend and description of a form field group.
Props for the data, field naming and rendering of a dynamic form list.
Information for one field passed to the list rendering function.
Methods for inserting, removing, moving and updating dynamic form list entries.
Props for presenting field validation errors together.
The field identity, label and message of an error summary entry.
State and form event handlers returned by useFormValidation.
Configuration for application validation, submission callbacks and error handling.