Form Component

API reference for the <Form /> component — props, the onSubmit caveat, and the FormRef imperative handle.

View as Markdown

<Form /> Component

The main entry point of @saastro/forms. It takes a FormConfig, builds the Zod schema, wires up React Hook Form, renders the current step’s fields through your injected UI components, and runs the full submit pipeline.

import { Form } from '@saastro/forms';

<Form
  config={config}
  components={import.meta.glob('@/components/ui/*.tsx', { eager: true })}
/>;

Props

<Form> accepts nine props (FormProps):

Prop Type Default Description
config FormConfig — required The full form configuration: fields, steps, layout, buttons, submit actions, plugins. See Types Reference
components ComponentOverrides | GlobModules undefined UI components for the form — a component object or a raw import.meta.glob(..., { eager: true }) result (auto-detected)
onSubmit (values: Record<string, unknown>) => void | Promise<void> undefined Called once after every successful submission — submit button or Enter — with the processed values. See below
onError (error: Error) => void undefined Called once when a submission fails, or when your onSubmit throws. See below
className string undefined CSS class for the <form> element. When omitted, the form falls back to w-full
action string undefined Progressive enhancement: action of the <form>, so the form still submits when JS never runs. Inert while JS works. See below
method 'get' | 'post' undefined Goes with action. Omitted from the markup when not passed
enctype 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain' undefined Goes with action; only emitted when action is set. Use multipart/form-data only if the target accepts it. See below
nativeFields Record<string, string> undefined Extra hidden inputs that travel only in the native submit (e.g. { _redirect: '/thanks' }). Only rendered with action. See below

config

The only required prop. Build it with FormBuilder or write the object by hand — the shape is documented in the Types Reference. Note that the identifier property is formId (not id), steps is a Record<string, Step> keyed by step id, and column count lives under layout.

Most behavior callbacks live on the config, not on the component: config.onSuccess, config.onError, config.onStepChange, config.successMessage, config.redirect, and so on.

components

Accepts either form:

// 1. Glob modules (Vite) — auto-discovers every component in the folder.
//    `eager: true` is required.
<Form config={config} components={import.meta.glob('@/components/ui/*.tsx', { eager: true })} />

// 2. Explicit component object — provide only what your form needs
<Form config={config} components={{ Input, Button, Field, FieldLabel, FieldDescription, FieldError, FormField, FormControl }} />

If you render <Form> with no components prop and no surrounding provider, the form is not rendered — you get a “Missing UI Components” error panel with setup instructions instead. A partial registry renders the form, and any individually missing components show a per-field fallback with install instructions.

Provider precedence: inside a legacy ComponentProvider, the provider’s registry wins and the components prop is effectively ignored. Use one mechanism or the other. See Component System for all three injection modes.

onSubmit and onError

Both props are called by the library’s submit pipeline, which every submission goes through: the rendered submit button (deliberately type="button", so it can run the confirmation UX and per-step validation) and native submission (pressing Enter in a field). Each submission calls one of them exactly once.

  • onSubmit runs on the last step, after validation, field transforms, plugins and submit actions have succeeded, and before the success screen is shown. It receives the processed values — the same object config.onSuccess gets. If it returns a promise, the form stays in its loading state until it settles.
  • If the submission fails — a submit action, a config.submit handler or a plugin hook — the success screen is not shown, config.onError and the onError prop are both called with the error, and onSubmit is not called.
  • If your onSubmit throws, the data has already been sent: the error goes to the onError prop only, and the success screen is still shown (so the user doesn’t resubmit).
<Form
  config={config}
  onSubmit={async (values) => {
    await saveDraft(values);
  }}
  onError={(error) => console.error(error)}
/>

The config callbacks (config.onSuccess, config.onError) fire on the same submissions; use whichever belongs where your logic lives — the config travels with the form (Hub, builder), the props belong to the page that renders it.

Up to and including 0.21.0, onSubmit/onError were only wired to the native <form onSubmit> path, so clicking the submit button never called them.

See Submitting Forms for the full pipeline.

className

Applied to the underlying <form> element. Defaults to w-full when omitted. For styling fields and the grid, see Styling and Layout System.

action and method

A form rendered on the server — see initialSchema — is visible without JavaScript, but it does not submit: with no action, a native submit reloads the same URL and the values are gone. On a paid landing page that is a lost lead. These two props close that gap; the fields already carry their name, so the browser can serialize them on its own.

<Form
  config={config}
  components={components}
  action="https://submit.saastro.io/v1/acme/contact/submit"
  method="post"
/>

Two things to know before you reach for them:

  • They are inert while JavaScript works. handleSubmit from react-hook-form calls preventDefault(), so a working page still submits through the usual fetch path — the one that speaks application/json and knows about attachments and captcha. Omit them and the emitted <form> is byte-for-byte what it was before.
  • The target must accept application/x-www-form-urlencoded, which is the only thing a native <form> knows how to send. The Hub ingestion endpoint accepts it (and answers with a 303 redirect) only for forms that opted in with meta.nativeSubmit; any other form rejects it as native_submit_disabled, so pointing action at one would hand the visitor an error instead of nothing. That is why nothing is wired by default.

enctype and nativeFields

Both belong to the native submit and, like action, are inert while JavaScript works. enctype is only emitted together with action. nativeFields renders one <input type="hidden"> per entry — plain DOM inputs, not form fields: they never go through react-hook-form or the JS payload. An entry whose name collides with a field of the form is ignored with a warning.

<Form> itself does not police where you point it — it takes a plain FormConfig and also serves forms that never came from the Hub. The gate lives in <HubForm>, which owns the Hub schema: it drops action/method unless that schema carries meta.nativeSubmit, so a Hub form cannot render a submit the ingestion worker is going to reject.


Imperative Handle: FormRef

<Form> is a forwardRef component. Attach a ref to control the form from outside — prefill values, reset it, read the current values, or trigger validation:

import type { UseFormReturn } from 'react-hook-form';

interface FormRef {
  setValue: UseFormReturn['setValue']; // setValue(name, value, options?)
  reset: UseFormReturn['reset']; // reset(values?, options?) — raw RHF reset
  getValues: UseFormReturn['getValues']; // getValues() / getValues(name)
  trigger: UseFormReturn['trigger']; // trigger(name?) => Promise<boolean>
  resetForm: (options?: ResetFormOptions) => void; // granular reset (see below)
  getDirtyValues: () => Record<string, unknown>; // user-edited values only
  getDirtyPaths: () => string[]; // dirty leaf dot-paths
  isDirty: () => boolean;
  goToStep: (stepId: string) => boolean; // jump to a step by id
  getCurrentStep: () => string; // id of the step on screen
}
Method Signature Description
setValue (name, value, options?) => void Set a field’s value programmatically
reset (values?, options?) => void Raw RHF reset — note it cannot dismiss the success screen or clear the submit error
getValues (name?) => values Read current values — all of them, or a single field by name
trigger (name?) => Promise<boolean> Run validation for one field, several, or the whole form; resolves true when valid
resetForm (options?) => void Granular reset: RHF reset plus clearing the package’s submit state (success/error)
getDirtyValues () => Record<string, unknown> Values filtered to user-edited top-level fields (machine writes excluded)
getDirtyPaths () => string[] Dirty leaf dot-paths, e.g. ['email', 'contacts.0.name']
isDirty () => boolean Whether any field is user-dirty
goToStep (stepId) => boolean Jump to a step by id, without validating the current one. false for an unknown id or the step you are already on. Fires onStepChange; «Back» returns to where you jumped from
getCurrentStep () => string Id of the step being shown

Review step: review: true

A step with review: true renders a summary instead of fields: one block per step the visitor’s route has gone through (computed from the current values, so a branch that no longer applies disappears), each with an Edit button that calls goToStep. Put it last, usually with fields: []; the submit button is the review step’s own. Labels come from the reviewEdit / reviewEmpty messages (en/es).

steps: {
  datos: { title: 'Your details', fields: ['name', 'email'], defaultNext: 'review' },
  review: { title: 'Review', review: true, fields: [] },
}

Granular reset: resetForm(options?)

resetForm composes RHF’s reset with the package’s bespoke submit state. Each option maps to RHF’s KeepStateOptions — plus one package-specific flag:

Option Maps to Effect
values reset(values) New values (and new defaults, unless keepDefaultValues)
keepValues RHF keepValues Keep current values, reset the rest of the state
keepErrors RHF keepErrors Keep field validation errors
keepTouched RHF keepTouched Keep touched flags
keepDirty RHF keepDirty Keep dirty flags
keepDefaultValues RHF keepDefaultValues New values don’t become the new defaults
keepIsSubmitted RHF keepIsSubmitted Keep RHF’s isSubmitted flag
keepSubmitCount RHF keepSubmitCount Keep RHF’s submitCount
keepSubmitState (package) Don’t clear the success screen / submit error / actions result

Common recipes: resetForm() — full reset back to a pristine form view after a successful submit; resetForm({ keepValues: true }) — clear errors/flags but keep what the user typed; resetForm({ values }) — programmatic prefill.

Example

import { useRef } from 'react';
import { Form, FormBuilder, type FormRef } from '@saastro/forms';

const config = FormBuilder.create('newsletter')
  .addField('email', (f) => f.type('email').label('Email').required().email())
  .addStep('main', ['email'])
  .build();

export function Newsletter() {
  const formRef = useRef<FormRef>(null);

  return (
    <div>
      <button type="button" onClick={() => formRef.current?.setValue('email', 'jane@example.com')}>
        Prefill
      </button>
      <button type="button" onClick={() => formRef.current?.reset()}>
        Clear
      </button>
      <button type="button" onClick={() => console.log(formRef.current?.getValues())}>
        Log values
      </button>
      <button
        type="button"
        onClick={async () => {
          const valid = await formRef.current?.trigger();
          console.log(valid ? 'Valid' : 'Has errors');
        }}
      >
        Validate
      </button>

      <Form
        ref={formRef}
        config={config}
        components={import.meta.glob('@/components/ui/*.tsx', { eager: true })}
      />
    </div>
  );
}

trigger() validates and shows error messages, but it does not submit. There is no imperative submit method — submission goes through the rendered submit button. (To fire individual submit actions imperatively — outside the full pipeline — see manual submit action triggers.)


Success and error UI

After a successful submission, the entire form is replaced by a success panel. The default message is '✅ Thank you!' — one of the library’s built-in English defaults (along with button labels like Submit). Override it per form with config.successMessage, per locale via Internationalization, or globally with setDefaultMessages. When a submission fails, an error panel renders below the form with config.errorMessage (or its default).

String success/error messages are rendered as HTML, so successMessage: 'Done! <a href="/next">Continue</a>' works. The HTML is sanitized — the same sanitizeHtml that labels and the html field go through (since 0.21 the html field is no longer an unsanitized escape hatch; code-authored forms opt out per block with .trustedHtml()).

The sanitizer is an allowlist rebuild: it tokenizes the markup with a strict grammar and re-emits only what it recognises — anything it cannot parse is escaped to text rather than “cleaned”. It is pure (no DOM), so server and client produce identical output. Policy:

  • Tags — formatting and structure (p, a, b, ul, table, img, details…). script, style, iframe, svg, math, object, form, template and other executing/embedding elements are removed with their content; unknown tags are removed and their text kept.
  • Attributes — allowlist plus data-*/aria-*. All on* handlers, style, name, srcdoc, formaction, ping, background are dropped.
  • URLs — href/cite accept http, https, mailto, tel, sms and relative paths. <img src>/srcset accept https, relative paths and data:image/*; an external http: or //host image is dropped. Entities are decoded before the scheme check (&#106;avascript:, javascript&colon;) and control characters ignored.
  • target="_blank" gets rel="noopener noreferrer" added (existing rel tokens kept).
  • Comments, <!doctype>, processing instructions and malformed closing tags are dropped.

Hardened apps can replace the built-in sanitizer globally:

import DOMPurify from 'dompurify';
import { setHtmlSanitizer } from '@saastro/forms';

setHtmlSanitizer((html) => DOMPurify.sanitize(html));

Post-submit redirect

config.redirect (string or (values) => string) navigates after a successful submit — but only to a URL that passes isSafeRedirectUrl: a path starting with / (not // or /\, which browsers resolve to another host) or an absolute http:///https:// URL. javascript:, data:, mailto:, protocol-relative and scheme-less values (thanks) are ignored with a console.warn. The helper is exported for your own navigation code:

import { isSafeRedirectUrl } from '@saastro/forms';

isSafeRedirectUrl('/thanks');              // true
isSafeRedirectUrl('https://x.com/ok');     // true
isSafeRedirectUrl('javascript:alert(1)');  // false
isSafeRedirectUrl('//evil.example');       // false

  • Quickstart — Build and render your first form
  • Component System — All three component-injection modes and auto-discovery details
  • Submitting Forms — What happens when the user clicks submit
  • Types Reference — FormConfig and every other exported type
  • HubForm — A wrapper around <Form> that fetches its config from the hosted submit service