Skip to content

Quickstart: React

Terminal window
npm install @formancy/react @formancy/core @formancy/spec

React 19 is a peer dependency. The packages are ESM-only, so Node 22.12 or newer and any bundler from the last few years.

The playground app is the fastest place to poke at a live form, and the whole builder is in it. @formancy/builder-react is published, so embedding it in your own application needs no clone — this is the faster way to try it.

Terminal window
git clone https://github.com/sharkysan/formancy.ai.git
cd formancy.ai
corepack enable pnpm
pnpm install
pnpm build
pnpm --filter @formancy/playground dev

A form is a plain JSON document: a model (what the form collects) and optional logic (how it behaves). Display text rides on the model as label, either as a literal string or as a reference into the form’s i18n catalogue.

import { useState } from 'react'
import { createFormEngine } from '@formancy/core'
import { FormancyProvider, FormancyForm } from '@formancy/react'
import type { FormSchema } from '@formancy/spec'
const schema = {
specVersion: '1',
id: 'contact-us',
title: 'Contact us',
model: {
fields: [
{ key: 'name', type: 'text', label: 'Your name', required: true },
{ key: 'email', type: 'text', label: 'Email address', format: 'email', required: true },
{
key: 'reason',
type: 'select',
label: 'Reason for contact',
options: [
{ value: 'question', label: 'A question' },
{ value: 'invoice', label: 'A problem with an invoice' },
],
},
{ key: 'invoiceNumber', type: 'text', label: 'Invoice number' },
],
},
logic: {
rules: [{ target: 'invoiceNumber', kind: 'visible', cel: 'reason == "invoice"' }],
},
} satisfies FormSchema
export function ContactForm() {
// One engine per form instance, created once and kept for its lifetime.
const [engine] = useState(() =>
createFormEngine({
schema,
capabilities: {
now: () => Date.now(),
today: () => new Date().toISOString().slice(0, 10),
random: () => Math.random(),
},
}),
)
return (
<FormancyProvider engine={engine}>
<FormancyForm
onSubmit={(outcome) => {
if (outcome.ok) console.log('answers to send', outcome.data)
}}
/>
</FormancyProvider>
)
}

FormancyForm renders every field through unstyled built-in components (zero CSS; style them via the data-formancy-part attributes), shows validation errors once a field has been touched, and hides invoiceNumber until the reason is "invoice". When a rule hides a field, its answer is removed from the value by default (clearOnHide), so a hidden branch cannot smuggle data into the submission.

One exception, and it is the only one: a control sets the CSS it needs in order to work, never how it looks. The signature surface declares touch-action: none on the element, because a touch drag on a drawing surface is otherwise resolved as a scroll by the browser before any handler runs — so a signature drawn with a finger would pan the page instead. Its height, border, background and cursor are still yours.

<FormancyForm review /> puts a step between the last question and sending: where the form would send, it offers Check your answers. Pressing it validates the whole form as sending would; with a problem it goes to the problem, and without one it shows every answer in words under its question — an option by its label, a date as the reader writes one — each with a Change that returns to that question’s page and focuses it. The form is sent from there (0204). A question the form asks and nobody answered is listed too, as Not answered, so one skipped by mistake is seen; one a rule hides or disables is not asked and has no line (0214).

fieldAddition draws something of yours under a field, inside the form: a summary of the record a lookup points to, a link that opens it. It is called with each field’s path, a row’s field by its own (the path its wrapper carries in data-formancy-field-path), and what it returns is drawn as the last thing in that field’s wrapper, after its label, help, control and error, in a data-formancy-part="field-addition" the themes dress. Return nothing and nothing is drawn, not even the wrapper. The content renders inside the form, so it reads the field with useField (0233):

function Customer({ path }: { path: string }) {
const field = useField(path)
return field.value == null ? null : <a href={`/customers/${String(field.value)}`}>Open the customer</a>
}
const addition = (path: string) => (path === 'customer' ? <Customer path={path} /> : null)
<FormancyForm fieldAddition={addition} />

Keep the function a constant, outside the component or in useCallback: a new one on every render redraws every field’s addition. It adds no role and no name, and no control is described by it: your links and buttons carry their own names. In a matrix or a ranking, which are drawn as a fieldset disabled with its field, your controls are disabled with the field.

Content of your own beside a field’s control

Section titled “Content of your own beside a field’s control”

fieldBeside draws something of yours beside a field’s box, on the box’s own line: a button that opens the record a lookup points to, or one that clears the answer. It is called with the path of each select and each typeahead, a row’s by its own, and what it returns is drawn after the box, the two in a data-formancy-part="field-control-row" and yours in a data-formancy-part="field-beside". Every theme draws a button there with the box as one field; anything else is laid out on the box’s line and not dressed. The field’s status and error stay under the box. Return nothing and nothing is wrapped, so the field is drawn as without it. No other control asks: a text field, a select whose source the deployment lacks and the fieldsets draw no row (0237):

const CROSS = 'M4.28 3.22 8 6.94l3.72-3.72 1.06 1.06L9.06 8l3.72 3.72-1.06 1.06L8 9.06l-3.72 3.72-1.06-1.06L6.94 8 3.22 4.28z'
function Clear({ path }: { path: string }) {
const field = useField(path)
const unavailable = field.value == null || field.disabled
return (
<button
type="button"
aria-label="Clear the country"
title="Clear the country"
aria-disabled={unavailable ? 'true' : undefined}
onClick={() => {
if (!unavailable) field.setValue(null)
}}
>
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path d={CROSS} />
</svg>
</button>
)
}
const beside = (path: string) => (path === 'country' ? <Clear path={path} /> : null)
<FormancyForm fieldBeside={beside} />

A button there is the box’s height and at least 44px wide, and an svg in it is sized to the text and filled in the button’s colour, so an icon needs no styling of yours. The themes draw it unavailable as :disabled and as aria-disabled="true"; the second keeps it in the keyboard’s order, so a button that becomes unavailable while the keyboard is on it, as a Clear does once pressed, keeps the keyboard rather than dropping it to the page.

Give content for a path or nothing, and keep to it: content for a path that had none, or none for one that had some, draws the box again, and a person in it loses the keyboard. To show nothing for a while, give a component that draws nothing, which keeps the box, and whose empty place every theme hides. Keep the function a constant, as for fieldAddition. It adds no role and no name and describes no control, and it disables nothing: beside a field a rule disables your button stays operable, so one that changes the answer reads field.disabled first, as the Clear above does.

The questions are yours. The words around them — Next, Back, Submit, a repeater’s Add and Remove and which row a button acts on, the error summary’s heading, and what a field announces while a file is sent or a list is searched — are the renderer’s, and they are in the language the questions are read in: the engine’s locale when the document has a catalogue for it, and the document’s default when it has not — never the browser’s. Build the engine in German and the buttons are German; English, German and French ship.

const engine = createFormEngine({ schema, locale: 'de', capabilities })
<FormancyProvider engine={engine}>
<FormancyForm /> {/* "Weiter", "Zurück", "Absenden" */}
</FormancyProvider>

A language that does not ship, or a word you want said differently, is yours to give, by locale, a message at a time — anything you leave out is English. English is a language like the others: en changes it, on a form with no catalogue too.

import type { FormWordsByLocale } from '@formancy/react'
// A constant: a new object on every render is a new language for every control below.
const WORDS: FormWordsByLocale = {
it: { 'form.next': 'Avanti', 'form.back': 'Indietro', 'form.submit': 'Invia' },
de: { 'form.submit': 'Senden' },
en: { 'form.submit': 'Send' },
}
<FormancyProvider engine={engine} words={WORDS}>

Every id, with its English, is FORM_WORDS in @formancy/core/words; FORM_WORDS_DE and FORM_WORDS_FR are the shipped translations. Your own words still win where you gave them: submitLabel names the submit button, and a repeater’s addLabel and removeLabel in the document name its buttons. A component of your own reads the same words with useFormText(). ResumeNotice speaks the form’s language inside the form’s FormancyProvider, and English outside it. A field’s errors are said in the same language: the engine reports a code, such as minLength, and the field shows “Enter at least 5 characters.” with its own limit in it — error.minLength among those ids, changed like any other word (0191). One thing is not the renderer’s to translate: addLabel is a plain string in one language (0171).

Element ids come from the engine, minted from the form’s id — which is what makes them deterministic and stable under server rendering. Two engines built from one schema therefore mint identical ids, and a duplicate id does not merely duplicate: <label for> resolves to the first match in the document, so every control in the second form loses its accessible name.

Pass formId when one page shows the same form twice:

const first = createFormEngine({ schema, formId: 'applicant-1', capabilities })
const second = createFormEngine({ schema, formId: 'applicant-2', capabilities })

It changes nothing about the document — same schema, same hash, and a submission still binds to the version it was rendered against. Leave it out for the usual case of one form on a page and the form’s own id is used.

The playground does exactly this to show one schema under the React and Angular renderers at once.

The engine never reads an ambient clock or random source. now(), today() and random() in expressions are injected through the capabilities option, and the engine refuses to start without one when the schema has logic rules.

This is not ceremony. The server replays every submission through the same engine to recompute calculated values and strip hidden branches — and a replay is only meaningful if the same expression over the same values produces the same result, byte for byte. A clock read inside the engine would make that impossible, so the clock is handed in from outside: Date.now in the browser, one pinned clock per request on the server. Each capability is drawn once per evaluation pass and frozen, so a form with fifty computed fields agrees with itself about what time it is.

useField binds one field and re-renders exactly when that field’s snapshot changes — the engine’s snapshots are identity-stable, which is what lets useSyncExternalStore work without memoisation. The binding carries prop getters with all the ARIA wiring precomputed:

import { useField } from '@formancy/react'
function EmailField({ path, label }: { path: string; label: string }) {
const field = useField(path)
if (!field.visible) return null
return (
<div>
<label {...field.labelProps}>{label}</label>
<input
type="email"
{...field.controlProps}
value={typeof field.value === 'string' ? field.value : ''}
onChange={(event) => field.setValue(event.target.value)}
onBlur={() => field.touch()}
/>
{field.touched && field.errors.length > 0 ? (
<p {...field.errorProps}>{field.errors.join(', ')}</p>
) : null}
</div>
)
}

Register it for one path — or for a whole type — and FormancyForm will use it instead of the default:

<FormancyForm registry={{ byPath: { email: EmailField } }} />

Per-path entries beat per-type entries beat the built-in defaults. A design system replaces the entire visual layer by handing in a registry, without forking anything.

Put the field’s id on what you draw. controlProps.id is the engine’s control id, and the links in <ErrorSummary />, and a submit through useSubmit() that fails, move focus by it. Spread it on the control, or, for a field answered by several controls, as a radio group or a set of tick boxes is, put field.ids.control on the group around them: a group takes no focus, so focus moves to the first control inside. A component that draws the id nowhere is a field the summary names and cannot take anybody to. The built-in controls do the same — a group carries it on its fieldset, and a signature on the box its name is typed into (0186).

A field a computed rule writes has field.readOnly set, and setValue on it does nothing: its value is the rule’s. Draw it with readOnly as the built-in controls do, or the person types into a box that does not keep what they type (logic). A control you register by type for a type with no read-only box — a tick box, a choice, a list — is not mounted for such a field: the renderer draws its answer in words instead. Register it for the field’s path to draw it yourself.

A time or an instant of your own, at a precision

Section titled “A time or an instant of your own, at a precision”

TypedTemporalInput is the box a time or a datetime with a precision is typed into, without the form around it: the control FormancyForm draws for such a field, for a host that keeps the answer itself, in a form library or a settings screen of its own. It takes the stored answer and reports the stored answer, so what it hands back is what you keep and what you pass in again.

import { TypedTemporalInput } from '@formancy/react'
<TypedTemporalInput
type="datetime"
precision={3}
value={answer} // '' or an instant such as 2026-11-15T13:03:27.415Z
onChange={(next) => setAnswer(next ?? '')} // null when it is emptied
aria-label="Started"
/>
  • type is time or datetime, and precision is 0 to 9, the field’s own.
  • value is the stored answer, and onChange receives the stored answer, or null when the box is emptied. A datetime is typed on the person’s own clock and reported as the UTC instant, its fraction copied digit for digit; an entry that stops short is reported as the text typed, for a shape check to refuse, never completed.
  • readOnly, placeholder, ref and the other props of an input — id, name, aria-*, onBlur — are passed to the box. Its placeholder is the mask unless you give one. The props type leaves out the ones the control decides: type, always text; inputMode, numeric; value and defaultValue, which value above replaces; and onChange, onPaste and onDrop, through which it reads what is typed, pasted and dropped.
  • It reports only what the person types, pastes or drops, never on mount.
  • useRepeater(path) — row count, addRow, removeRow for a repeater, and canAdd and canRemove, which say whether its maxItems and minItems allow one more or one fewer; past either, addRow and removeRow throw. On a repeater a computed rule writes, both say false and the commands do nothing (0218). Drawing your own repeater from it, move focus yourself once a row’s change is drawn. The shipped one takes it into a new row, into the row now in a removed one’s place, or to Add when none is left, and keeps it on a moved row’s button (0219).
  • useWizard() — page state and next/back/goTo for a paged form; next validates only the current page, submit validates everything.
  • useSubmit() — returns a submit function producing { ok, errors }.
  • useGoToField() — returns a function that takes a field’s path, email or guests[1].name, and takes the person there as the error summary’s links do: to the field’s page on a paged form, then into its control once that page is drawn — a group’s first option, and past a tab a layout hides it behind. For a list of your own, of what is still missing, say (0213).
  • <ErrorSummary /> — the errors a user should currently see (touched and invalid), in document order.

Note that errors on a field are codes ("required", "minLength", "pattern"…), not sentences: they are the engine’s vocabulary, and what the API returns. What a person reads is errorSentence(text, def, code) from @formancy/core/words, which the shipped controls call and a control of your own can too (0191).

A model’s edit, checked against your examples

Section titled “A model’s edit, checked against your examples”

@formancy/builder-react is the builder. Two of its panes belong together: ScenarioPane runs a form’s examples after every edit, and PromptPane asks your model for a change and holds the answer for review (agents). Give them the same examples:

import { PromptPane, ScenarioPane } from '@formancy/builder-react'
<>
<PromptPane session={session} ask={askModel} scenarios={scenarios} initialValue={sample} />
<ScenarioPane
session={session}
scenarios={scenarios}
onChange={setScenarios}
initialValue={sample}
/>
</>

scenarios, initialValue and mode mean the same on both. With them the prompt pane runs the examples against the form as it is and as the answer would leave it, before anybody presses Apply. The review’s heading names each example that would stop holding, and the status names those and any that would hold again. Apply stays enabled, because a rule changed on purpose stops its old example holding. A rule no example pins gets no warning, and without scenarios the review says nothing about examples (0159).

A pane drawn under a tab stops its run when the tab changes. To keep a model’s turn going while the person looks elsewhere, hold the run above the tabs with createPromptRun() and pass it as run (agents). The translations pane takes a createTranslationRun() as run, and the scenario pane a createDraftRun() as drafting, for the same reason (0164).

Examples, drafted from what you say the form should do

Section titled “Examples, drafted from what you say the form should do”

A form with no examples gets nothing from either pane. Give ScenarioPane a model as well as onChange, and it drafts some:

<ScenarioPane
session={session}
scenarios={scenarios}
onChange={setScenarios}
initialValue={sample}
ask={askModel}
/>

The person says what the form should do, in their own words, and presses Draft examples. The model is shown the form’s fields — the path an example names each one by, its type, its label and its options — the error codes the engine reports, where examples start and those words. It is never shown a rule, a pattern, a bound or which fields are required: a model shown the rule writes the example the rule passes, and that example agrees with the rule whether it is right or wrong.

Each draft is listed with what it sets and expects, and with the engine’s verdict on the form as it is now — run with the pane’s own initialValue and mode, so it is the verdict the list gives it once kept, recomputed when the form changes. Nothing reaches onChange until Keep. A draft that does not hold can be kept: that is the person saying the example is right and the form is not. A name already in the list, or a field the form does not have, cannot be kept. Items of the answer that are not examples are listed with why, and do not cost the rest; a model that declines has its reason quoted. With a relay as ask, the request is carried by hand like the prompt pane’s (agents), and the part tells the person to start a new chat for it: a model that has already seen the form there has seen its rules. One relay for both panes carries one turn, so whichever asks second is told another request is waiting. ScenarioDrafts is the part on its own, for a host that places it elsewhere (0162).

Next: self-host the backend and post the form’s submissions to it, or read how the schema is structured.