GitHub

Data Form

A form built by hand or from field configuration, with linked fields, validation, lists, steps and overlays.

Loading example…

Installation

pnpm dlx shadcn@latest add @sui/data-form

Install with the shadcn CLI or use the shared @workspace/ui package. Follow the installation guide to configure the registry, load styles, and choose import aliases.

import { DataForm, DataFormItem } from "@workspace/ui/components/data-form"

Usage

Wrap any control in DataFormItem. It adds the label, description and error from Field, binds the value and blur, and sets aria-invalid, aria-required and aria-describedby. The control keeps its own props.

<DataForm onFinish={async (values) => save(values)}>
  <DataFormItem name="title" label="Title" required>
    <Input placeholder="e.g. Export fails on Safari" />
  </DataFormItem>
  <DataFormItem name="urgent" label="Blocks my work">
    <Checkbox />
  </DataFormItem>
</DataForm>

Or describe fields once and let their valueType pick the control. Both write the same markup and can be mixed: fields render first, then children.

<DataForm
  fields={[
    { name: "name", label: "Name", required: true },
    { name: "role", label: "Role", valueType: "select", valueEnum: { admin: "Admin", viewer: "Viewer" } },
    { name: "notifications", label: "Email me product updates", valueType: "switch" },
  ]}
  onFinish={save}
/>

DataForm is the default arrangement of smaller parts. Compose them when a page needs a different one:

Loading example…
PartRenders
DataFormRootThe <form> and its providers; takes form, layout, columns and collapse
DataFormFieldsThe form's fields, or the ones passed
DataFormFieldOne field by its value type, the same shape as an item of fields
DataFormItemAny control, framed and bound
DataFormGroupA titled group, separated by space rather than a card
DataFormListRows of the same fields
DataFormFieldSetSeveral controls that make one value
DataFormDependencyContent drawn from the values of named fields
DataFormErrorSummaryThe form's own error, and a list of fields after a failed submit of a long form
DataFormFooter, DataFormReset, DataFormSubmitThe buttons: Reset before Submit, a spinner while the request is in flight
DataFormCancelCancel, when a plugin such as dialog() gives the form one
DataFormFillMarks a fixed-height frame: inside it the fields scroll and the footer stays in view

Value types

Each value type has an edit control and a read view. The read view is used by readonly forms and shows empty values as a muted dash.

valueTypeControlValue
text, password, textareaInput, Textareastring
digit, money, percentNumber input; read with Intl.NumberFormat and fieldProps.formatnumber
digitRangeTwo number inputs[from, to]
select, multiSelectSelect; a search box appears past 10 optionsstring, string[]
radio, checkboxGroupRadioGroup, Checkbox liststring, string[]
checkbox, switch, booleanCheckbox, Switch, Yes/No selectboolean
date, dateTime, dateRange, dateTimeRangeDatePickerDate, [Date, Date]
time, timeRangeTimePicker"hh:mm", [from, to]
color, tags, sliderColorPicker, TagInput, Sliderstring, string[], number

number, enum, numberRange, datetime and datetimeRange are aliases of digit, select, digitRange, dateTime and dateTimeRange, the names DataTable uses. Date types keep Date values; fieldProps.valueFormat: "string" keeps local yyyy-mm-dd strings instead.

Every built-in type, in its edit and read-only views:

Loading example…

Pick by option count, as the data entry pattern suggests: switch or checkbox for on and off, radio for two to five options, select for more. Register your own types once with ValueTypeProvider; DataForm reads them by name.

<ValueTypeProvider valueTypes={{ rating: { edit: (props) => <Rating {...props} />, text: ({ value }) => `${value} / 5` } }}>
  <App />
</ValueTypeProvider>

A definition can also set lightMode (where it sits in a light row), prefix (it shows a label inside), dateMode (how its dates are submitted) and persist: false (kept out of drafts, as passwords are).

Options come from request, then options, then valueEnum. valueEnum also gives each option a badge color in read-only views.

Linked fields

Link fields with functions or with JSON. A function receives the current values:

{
  name: "city",
  valueType: "select",
  dependencies: ["province"],
  clearOnChange: true,
  disabled: (values) => !values.province,
  options: (values) => citiesOf(values.province),
}

JSON reactions use the same twelve operators as DataTable filters and never evaluate code, so a server can send them:

{
  "name": "taxId",
  "reactions": [{
    "when": { "logic": "and", "rules": [{ "field": "invoice", "operator": "eq", "value": "company" }] },
    "fulfill": { "required": true },
    "otherwise": { "hidden": true, "value": null }
  }]
}
Loading example…

Each field follows only the values it reads, so a change renders the fields that depend on it and no others. Reactions declare their fields; list dependencies for function props, or the field follows every value. clearOnChange empties a field when someone edits a field it depends on; loading, restoring a draft or reset set values that belong together and clear nothing.

When the same property is set in several places, the later one wins: the field's own value, JSON reactions, function props, the form's readonly, then access. A hidden field keeps its value but is left out of submission and validation; fields on another step or behind Expand are only out of view, so they are sent and checked.

serializeFields turns fields into JSON and stops at the first function, naming its path. parseFields checks JSON against dataFormSchema and rejects value types that are not registered.

Validation

Fields validate when they lose focus and on submit, never on each keystroke, and the message appears under the field. required adds a check, an asterisk and aria-required. validators take a function or a Standard Schema per phase, and onChangeAsync waits debounceMs after typing stops.

Pass a schema such as Zod to validator to check the whole form on submit, then on blur. Errors for hidden fields are dropped.

onFinish receives the payload. Return or throw { fields, form } and the messages land under their fields and in an alert above the form; editing a field clears its message.

Loading example…

After a failed submit, focus moves to the first invalid field. In a form with three or more errors, a summary lists them, and each entry moves focus to its field.

Lists and groups

DataFormList repeats a set of fields. Adding a row moves focus into it, removing one moves focus to a neighbor, and both are announced to screen readers. Set min, max and sortable.

Loading example…

Read-only and permissions

readonly shows every value through its read view, so one set of fields serves both a detail page and an edit page. access maps field names, or a function, to edit, readonly or hidden; it wins over every other rule. An inline map can be written in place; memoize a function.

Loading example…

Read-only values are submitted, as an edit form needs ids. Use transform, or access to hide a field, to leave one out.

Steps

steps() splits the form. Fields join a step with step. Next validates the current step only, Previous keeps the values, and the last step submits everything. Every field stays mounted, so a failed final submit returns to the first step with an error.

Loading example…

Dialogs and sheets

dialog() puts the form in a Dialog, and a bottom Drawer on phones; sheet() opens it from an edge while the list stays in view. Both stay mounted, keep the buttons in view while the fields scroll, ask before discarding changes, and close and reset after a successful submit. Cancel takes Reset's place, and joins the steps' Previous and Next when steps() is in the list too, in either order.

Loading example…

Filters

layout="grid" with collapse is a query form: the first fields and an Expand button, then Reset and Search. Expanding and collapsing animate the height while the extra fields fade in, and drop the motion under reduced motion; collapsed fields stay mounted, so their values and validation remain. layout="light" with submitOn="change" shows each field as a compact button that sums up its value; fields past collapse.count share one Filters popover and apply together. Set lightMode per field to choose: inline puts the control itself on the row with its label, popover a compact button that opens it, and more the Filters popover whatever the count. Date and time pickers are inline by default, other controls popover. Data Table's query form and toolbar filters are these two layouts.

Loading example…

Submission

The payload leaves out hidden fields, then applies each field's transform (return an object to replace the field with several keys, such as { startAt, endAt }), writes dates as local yyyy-mm-dd (dateFormatter), drops null and undefined with omitNil, and finally runs the form's transform. convertValue reads stored values into the shape a control uses; it runs only on values that are present, so give a starting value with initialValue.

request loads the initial values, with skeletons in place of the controls. Reset returns to the values request or reset(values) last set. Cmd/Ctrl + Enter submits.

Plugins

PluginAdds
dialog(options), sheet(options)An overlay with title, description, trigger, open, onOpenChange
steps(options)Steps from items: [{ key, title, description }]; current and onCurrentChange to control them
persistDraft({ key })Keeps unsent changes in localStorage, with the current step, and offers to restore them; a successful submit clears the draft. Passwords and hidden fields are never stored
confirmLeave()Asks before leaving the page with unsaved changes

A plugin is an object with a name and any of setup (runs as a hook), wrapForm, slots (header, footer), isFieldShown, beforeSubmit, onSubmitInvalid, onFinished and onReset. onCancel gives every footer a Cancel button, and persistKeys names the plugin state a saved draft keeps, as the steps keep the current step. Memoize the plugin list.

Labels

English is the default. Pass labels={dataFormLabelsZhCN} for Chinese, or override individual entries. Validation messages from a schema come from the schema.

API

PropDescription
fieldsField configuration.
childrenContent after fields, such as DataFormItem.
defaultValuesInitial values.
requestLoads the initial values.
onFinishReceives the payload; may return { fields, form }.
onFinishFailedCalled when validation fails or onFinish throws.
validatorA Standard Schema or function for the whole form.
layoutvertical (default), horizontal, grid or light.
columnsGrid columns on wide containers.
collapsetrue, or { count, defaultCollapsed }.
submitOnsubmit (default) or change.
readonly, accessRead-only views and per-field permissions.
submitterfalse hides the buttons; a node replaces them.
stickyFooterKeeps the buttons in view on a long page.
transform, convertValue, dateFormatter, omitNilPayload shaping.
plugins, labels, valueTypesPlugins, text and custom value types.
actionRefReceives { submit, reset, validate, validateFields, setValues, setErrors }. validate() runs field and form validators, as submit does, and resolves true when the form is valid.
formA form from useDataForm, instead of the options above.

Field configuration:

FieldDescription
nameA dot or bracket path.
label, description, tooltip, placeholderText around the control.
valueType, valueEnum, options, request, fieldPropsThe control and its options.
hidden, required, disabled, readonlyA value or a function of the values.
reactions, dependencies, clearOnChangeLinking.
validatorsonBlur, onSubmit, onChange, onBlurAsync, onChangeAsync, debounceMs.
initialValue, convertValue, transformValues in and out.
colSpan, step, className, renderPlacement and a custom control.
lightModeinline, popover or more in a light layout.

The design draws on Ant Design ProForm for field configuration, value types and overlay forms, and on Formily for field reactions; state runs on TanStack Form.