<Form />

Form is the first item in the array returned by setupForm.

const [ 
  Form, 
  defineConfig,
  Section,
] = setupForm(); 
Tip

Form is used throughout this documentation, but since setupForm() returns an array, you can name it anything.

Form bound to field mapping

When a Form is created, it is bound to a specific field mapping. This mapping defines which field types are available and how they are rendered.

By default, BlueForm provides a set of built-in structural field types (inline, section, array, hidden). Calling setupForm() with no arguments creates a form system that only includes these built-in types.

const [Form] = setupForm();

To extend the form with custom fields while keeping all built-in ones available, use defineMapping:

const [Form] = setupForm({
  fieldMapping: defineMapping({
    text: InputField,
    select: SelectField,
  }),
});

Any unknown field type will be caught at compile time.

config={{
  username: { type: "text",    },  // ✅ custom
  profile:  { type: "section", },  // ✅ built-in
  age:      { type: "number",  },  // ❌ compile-time error
}}

Form bound to a data model

Form is generic. Field keys must match the data model, and onSubmit always receives fully typed data.

<Form<LoginData>
  config={{
    username: { type: "text" },
    password: { type: "text" },
  }}
  onSubmit={(data) => {
    // data is inferred as LoginData
    data.username
    data.password
  }}
/>

Form props

config

The field configuration object that defines the structure of the form. Each key maps to one field entry, including its type, label, rules, render behavior, and any extra props.

See Field config below.

Submit lifecycle

submit ─┬─ validation fails ──────────────► onInvalid(errors)
        └─ validation passes ─► onSubmit ─┬─ resolves ─► onSubmitSuccess
                                          └─ throws ───► onSubmitFailure(error)

onSubmit

Called when the form is submitted and passes validation. Receives the typed form data, the full React Hook Form methods, and the optional submit event. It may be async:

onSubmit={(data, formMethods, event) => {
  console.log(data)
}}

Use this for submit-time effects such as API calls, persistence, navigation, or analytics. To derive a field from others while the user types, use the field's compute.

onSubmitSuccess

Called after onSubmit resolves without throwing. Receives the same arguments as onSubmit.

This is a good place for post-submit side effects such as reset(), toast notifications, or closing a dialog after a successful save.

onSubmitFailure

Added in v0.14.

Called when onSubmit (or onSubmitSuccess) throws or rejects — typically a failed API call. Receives the error, the submitted values and the form methods:

onSubmit={async (data) => {
  await api.save(data) // may throw
}}
onSubmitFailure={(error, values, form) => {
  form.setError("root.server", { message: getMessage(error) })
}}

onSubmitSuccess is skipped and formState.isSubmitSuccessful stays false. When onSubmitFailure is omitted the error is logged with console.error — it never becomes an unhandled promise rejection, so you don't need to wrap every onSubmit in try/catch.

onInvalid

Added in v0.14.

Called when submission is blocked because validation failed; onSubmit is not called. Receives the RHF errors object.

Use this to react to invalid submission attempts, for example by scrolling to the first error or showing a summary banner.

onSubmitError

Deprecated

Renamed to onInvalid because the old name suggested it also handled errors thrown by onSubmit — it never did (use onSubmitFailure for those). It still works and is ignored when onInvalid is set. It will be removed in 1.0.

defaultValues

Initial values for the form, passed to RHF useForm. This is the only place for them: formOptions does not accept defaultValues.

<Form defaultValues={{ username: "alice" }} ... />

Use this for initial edit-state data, server-provided defaults, or sensible empty-state values.

formOptions

Options passed to RHF useForm for this specific form instance. These merge over formOptions defined in setupForm and per-form values always win.

<Form formOptions={{ mode: "onSubmit", shouldUnregister: true }} ... />

Defaults set by BlueForm (RHF's differ): mode: "onTouched" (a field is validated after its first blur, then on every change) and reValidateMode: "onChange".

Common use cases:

  • mode to override the default validation trigger
  • resolver for a resolver-based library (Ajv, or any @hookform/resolvers one); for a Standard Schema, prefer the schema prop
  • shouldUnregister to control hidden or unmounted field retention

Use formOptions when you want BlueForm to keep handling rendering and field wiring, but still need lower-level RHF behavior control.

readOnly

When true, all fields in the form receive readOnly: true. It only adds read-only: with false (or omitted), each field keeps its own readOnly, so one form serves a view page (readOnly) and an edit page (readOnly={false}) while fields such as computed totals stay read-only on both.

This is a form-level hint for your field components. BlueForm passes the flag down, but each renderer is still responsible for deciding how read-only mode should look and behave.

onFormChange

Called whenever any field value changes. Receives the current full form values and the full RHF form methods.

This is most useful for autosave, external state sync, analytics, or debugging. Because it fires on every change, consider combining it with debounceMs for anything non-trivial.

onFieldChange

Called when a single field value changes. Receives a typed context object plus the full RHF form methods:

onFieldChange={({ name, value }) => {
  if (name === "country") analytics.track("country_changed", { value })
}}

The first argument contains:

FieldDescription
nameThe path of the field that just changed
valueThe new value of that field
valuesCurrent snapshot of the full form values
setValueRHF setValue helper for writing derived values
triggerRHF trigger helper for revalidation flows
formStateCurrent RHF formState snapshot

Use it for side effects (analytics, remote lookups). For a value derived from other fields, use compute instead of setValue here: it tracks dependencies, settles chains and keeps the form pristine on mount.

debounceMs

Delay in milliseconds before onFormChange and onFieldChange fire. Useful for debouncing side effects such as autosave, remote lookups, or expensive synchronization work. Set to 0 or omit to disable.

This affects the change hooks only. It does not change how RHF validation itself works.

The change hooks always call the latest callback you pass, so inline functions that close over component state are safe. A change still waiting for its debounce delay is flushed when the form unmounts (e.g. the user switches tab right after typing), so autosave never loses the last edit. To deliver it earlier — before navigating away, for instance — call ref.current.flushChanges().

renderRoot

Controls the outer form shell, usually the <form> element and any wrappers around it.

Can be provided per-form to override the value set in setupForm.

Important

If neither setupForm nor the <Form /> instance provides renderRoot, an error will be thrown at run time.

ref

The ref exposes the full RHF useForm return (reset, setValue, getValues, …) plus flushChanges(). Use useFormRef for a correctly typed ref:

import { useFormRef } from "react-headless-form"

const formRef = useFormRef<LoginData>()

<Form<LoginData> ref={formRef} config={config} />

formRef.current?.reset()
formRef.current?.flushChanges() // deliver a pending debounced change now

i18nConfig

Controls how labels, descriptions, and validation messages are translated.

Can be provided per-form to override the value set in setupForm.

Info

The only option that cannot be overridden is fieldMapping - it is fixed at setup time to preserve compile-time type safety.

Form accepts children

children accepts either a ReactNode or a render function that receives form methods - useful when rendering dynamic UI that depends on form state. It is rendered after the config-driven content, so it usually appears at the end of the form. Both the generated fields and this children content are passed together as the children of renderRoot.

// ReactNode - static
<Form config={config}>
  <button type="submit">Submit</button>
</Form>

// Render function - reactive, accesses form state
<Form config={config}>
  {({ formState, setValue }) => (
    <button type="submit" disabled={!formState.isDirty}>
      Submit
    </button>
  )}
</Form>

The render function receives the same curated set of form methods as renderRoot - see renderRoot for the full list.

Field config

Each entry in config describes a single field. All fields share a common set of options:

OptionTypeDescription
typestringField type - must match a key in fieldMapping or a built-in type
labelstring | TranslatableTextField label, passed through i18n pipeline
descriptionstring | TranslatableTextHelper text, passed through i18n pipeline
defaultValueanyInitial value for the field
rulesValidationRulesRHF validation rules - ignored when schema or formOptions.resolver is set
propsComponentProps<...>Extra props passed to the field component - typed against the component's prop interface
renderRenderFnPer-field render override - see render prop
visibleboolean | Condition | (values, ctx) => booleanControls field visibility - hidden fields unmount, so state retention depends on whether the field ever mounted and on RHF shouldUnregister
disabledboolean | Condition | (values, ctx) => booleanControls disabled state - disabled fields are excluded from the submit payload
readOnlybooleanField-level read-only state; a form-level readOnly can only add to it
requiredboolean | Condition | (values, ctx) => booleanUI-only required flag (e.g. to show *). Defaults to Boolean(rules.required). Does not add validation
depsPath[]Optional (inferred since v0.16). Overrides which paths re-run the visible / disabled / required functions and compute. See conditional rendering
compute(values, ctx) => valueDerives the field's value from other values. See computed fields
slots{ before?, after? }Extra UI rendered right before / after the field, inside its field context. See slots

visible and disabled can also be functions. In that case they receive the current form values and are re-evaluated when the values they read change:

email: {
  type: "text",
  visible: (values) => values.contactMethod === "email",
},
confirm: {
  type: "text",
  disabled: (values) => !values.password,
},

For the full runtime behavior - including hidden-from-start fields, defaultValue, and shouldUnregister - see conditional rendering.

rules uses standard React Hook Form validation rules. pattern additionally accepts a string — "^\\d+$" or "/^abc$/i" — so configs can be stored as plain data. They are ignored when schema or formOptions.resolver is set: keep all validation in the schema.

username: {
  type: "text",
  rules: {
    required: "Username is required",
    minLength: { value: 3, message: "At least 3 characters" },
  },
}

Slots

Added in v0.14.

slots renders extra UI next to one specific field without replacing it via render. Slot content is rendered inside the field's context, so a slot component can call useField(), and a function slot receives the live field props (including value). On array fields a function slot receives the array's metadata and its errorMessage:

note: {
  type: "textarea",
  label: "Note",
  slots: {
    before: <Hint>Visible to the student</Hint>,
    after: ({ value }) => <ToneChecker text={value} />,
  },
},

For one-off markup between fields, prefer a section or an inline field; use slots when the extra UI belongs to a field (and needs its value).