Forms
A typed form factory, a registry field kit, and Zod validation on a shadcn-style layout
@zeno-lib/forms is a typed layer over TanStack Form
and Zod. The headless core (the form factory, validation, and schema
helpers) ships on npm and is UI-free. The shadcn CLI copies the field components (built on
shadcn primitives) into your repo from the registry, so you own and restyle them. You get type-safe
field names, a submit button that disables itself during submit, and a single schema prop
instead of hand-wired validators.
Setup
Add the field kit and the create-form composition with the shadcn CLI, then install the headless
core:
pnpm dlx shadcn@latest add zeno-lib/zeno/create-form
pnpm add @zeno-lib/formscreate-form passes your installed fields to the factory and exports the useForm hook. Import
it from wherever you added it. The examples below import the package's own copy of the same file,
@zeno-lib/forms/create-form.
Quick start
A newsletter form, validated with Zod:
"use client"
import { Form, FormProvider, useForm } from "@zeno-lib/forms/create-form"
import { z } from "zod"
const schema = z.object({
email: z.email("Enter a valid email"),
})
export function Newsletter() {
const form = useForm({
onSubmit: async ({ value }) => {
await subscribe(value.email)
},
schema,
})
const { EmailField, SubmitButton } = form
return (
<FormProvider form={form}>
<Form>
<EmailField name="email" placeholder="you@zeno.dev" />
<SubmitButton>Subscribe</SubmitButton>
</Form>
</FormProvider>
)
}Three pieces to know:
useForm({ defaultValues, schema, onSubmit })returns the form with typed field components attached.nameprops autocomplete againstdefaultValues, andvaluetypes match what your schema produces.<FormProvider form={form}>lets every destructured component (EmailField,SubmitButton, …) resolve the form from React context.<Form>renders the<form>element and callsform.handleSubmit()on submit. ASubmitButtoninside it disables itself and shows a spinner during submit, with no props to pass.
Destructure the components
The field components on form are stable across renders, so destructure
them at the top of your component and write <EmailField> rather than
<form.EmailField>:
const form = useForm({ /* … */ })
const { EmailField, PasswordField, SubmitButton } = form
return (
<FormProvider form={form}>
<Form>
<FieldGroup>
<EmailField name="email" />
<PasswordField name="password" />
</FieldGroup>
<SubmitButton>Sign in</SubmitButton>
</Form>
</FormProvider>
)Like an import block, the destructure line lists every field the
component uses. This is the recommended pattern in
@zeno-lib/forms, and it differs from upstream TanStack Form (which favors
form.EmailField).
Validation with Zod
Pass any Standard Schema to the schema
prop. Zod, Valibot, and ArkType all work:
import { z } from "zod"
const schema = z.object({
email: z.email(),
password: z.string().min(8, "At least 8 characters"),
})
const form = useForm({
schema,
onSubmit: async ({ value }) => {
// `value` is typed from the schema
},
})A second prop, validators, controls when errors appear:
'blur-then-change' (default), 'change', 'blur', or 'submit'. With
the default, a field shows no error until its first blur, then its errors
update as the user types. See
Validation modes for
the full breakdown.
Defaults from the schema
When you pass a Zod schema, useForm derives initial values from it
so you don't repeat them in defaultValues:
.default(value)becomes the field's initial value, so changing the default in the schema changes the form.- Strings (
z.string(),z.email(),z.url(), …) and arrays (z.array(...)) without a.default(...)initialise as""and[]respectively, so React inputs render controlled. - Numbers, booleans, dates, enums, files without a
.default(...)are skipped, because their empty value depends on your domain (0,false,today). Supply them indefaultValues, the only way to tell the form which empty value you want. - Anything you put in
defaultValuesalways wins on conflict; the schema only fills the keys you leave out. - Nested
z.object(...)follows the same rules, anduseFormdeep-merges a partial nested object fromdefaultValuesinto the schema-derived shape.
const schema = z.object({
email: z.email(), // → ""
password: z.string().min(8), // → ""
role: z.string().default("member"), // → "member"
newsletter: z.boolean().optional(), // skipped (boolean) → user supplies
})
const form = useForm({
defaultValues: { newsletter: false }, // only the boolean needs spelling out
schema,
})Open an edit form with the record as read. The form keeps the keys its
schema describes, at every depth and in every array row, and drops the
rest, so a .strict() schema doesn't reject the row's id or createdAt
on submit. Read the id from the record, not from value. A key the
record lacks still gets its schema default. A FormDialog session and
submitAction's reset keep the same keys. Where the schema doesn't say
which keys belong (a union, a record, a loose or catchall object), the
value is kept as is.
Schema defaults and that key filtering are Zod-only. With a Valibot or
ArkType schema, the hook uses your defaultValues as they are.
Focus on submit
When a submit fails validation, <Form> moves focus to the first control
with aria-invalid="true" inside the submitted <form> element. This
follows the pattern from TanStack Form's
focus management guide.
Because the lookup only searches the submitted form, a form in a dialog
never moves focus to the page behind it, and a submit from an external
<button form="…"> works the same way. When the invalid element is a
group root that can't take focus itself (radio group, slider), <Form>
focuses its first tabbable child. Field errors that
submitAction
puts on fields count too. An onSubmitInvalid you pass goes to
TanStack Form unchanged. The form-dialog item does the same for its own
<form>. In a <form> of your own that calls handleSubmit, call
focusFirstInvalid(formElement) from @zeno-lib/forms/lib/focus-first-invalid
once the submit leaves form.state.isValid false.
A submit that throws leaves focus where it was, and <FormError />
announces the error. A
form-level error
is announced the same way, but it keeps SubmitButton disabled until the
next edit, so focus can't go back to it.
Custom fields
When the field kit doesn't cover what you need, ControlField binds any
controlled component in the kit's field layout, and useFieldControl gives a
field component of your own the same wiring. See
Custom fields.
Default props
Set your app's defaults for a field or form component once, in the
createZenoForm call of your create-form file, rather than wrapping the
component or editing its file:
const { useAppFields, useAppForm, useForm, withFieldGroup, withForm } =
createZenoForm({
defaultProps: {
FormError: { submitErrorMessage: "Not saved. Try again later." },
MoneyField: { currency: "CHF", locale: "de-CH" },
PercentageField: { scale: "fraction" },
},
fieldComponents: { /* … */ },
formComponents: { /* … */ },
})- A prop passed at the call site wins, so
<MoneyField currency="EUR" />shows euros. A prop passed asundefinedkeeps the default, as a destructuring default would. - Each component's defaults take only that component's optional props, so
another field's prop, a wrong value or a required prop (
SelectField'schildren) fails the type check. - Defaults belong to the component they are keyed by. The fields built on
InputField, such asEmailFieldandMoneyField, don't takeInputField's. - The defaults apply however the component renders: from
useForm's form, a section'sformor a group'sgroup, fromuseAppFields, or asfield.MoneyFieldinsideform.AppField. - The field files stay as the registry ships them. The
create-formitem shipscreate-form.tsxwith them, though, so when you re-add it to update the fields, carry yourdefaultPropsover to the new file. - A default is a fixed value. One that depends on another prop, such as a
maxthat followsscale, still belongs at the call site.
Every string the kit's own files render is a prop: submitErrorMessage,
emptyMessage, clearLabel, placeholder, label on EmailField and
PasswordField, and ResetButton's children. So the same defaults
translate the kit for an app with one UI language. FormDialog takes its
own defaults from
FormDialogProvider.
The shadcn primitives keep their own labels, such as the spinner's
"Loading" and the combobox clear button's "Clear": translate those in
your components/ui files.
Splitting a large form
Split a long form into sections with withForm, from TanStack Form's
form composition.
A section declares the values it expects, and the parent passes it the form
from useForm, with or without a schema:
"use client"
import {
Form,
FormProvider,
useForm,
withForm,
} from "@zeno-lib/forms/create-form"
import { FieldLegend, FieldSet } from "@zeno-lib/ui/field"
import { z } from "zod"
const schema = z.object({
address: z.object({ city: z.string(), street: z.string() }),
name: z.string(),
})
type Profile = z.infer<typeof schema>
const AddressSection = withForm({
// Only types `form`: the section works on the form it is given.
defaultValues: {} as Profile,
props: { title: "Address" },
render: ({ form, title }) => (
<FieldSet>
<FieldLegend>{title}</FieldLegend>
<form.InputField label="Street" name="address.street" />
<form.InputField label="City" name="address.city" />
</FieldSet>
),
})
export function ProfileForm() {
const form = useForm({
onSubmit: ({ value }) => saveProfile(value),
schema,
})
const { InputField, SubmitButton } = form
return (
<FormProvider form={form}>
<Form>
<InputField label="Name" name="name" />
<AddressSection form={form} title="Home address" />
<SubmitButton>Save</SubmitButton>
</Form>
</FormProvider>
)
}- TanStack never applies the section's
defaultValues; they only typeform. Pass a value of the form's type, as above, or spread theformOptionsyouruseFormcall shares. - A form with other values fails the type check where the parent renders the section.
- The section's
formcarries the same typed fields asuseForm's, default props included.useAppFields(form)gives them to a form typed some other way. renderruns inside a component, so it can call hooks. Keep it an arrow function, because Biome's hook rule doesn't recognize arender() {}method as a component.- For a group of fields that several forms reuse at different paths, such
as an address under both
billingandshipping, usewithFieldGroup.
Reusing a group of fields
withFieldGroup, from TanStack Form's
form composition,
declares fields relative to the group. A form renders it at any path of the
same shape, and the group's group carries the fields, typed by the group's
own values:
const AddressFields = withFieldGroup({
defaultValues: { city: "", street: "" },
props: { title: "Address" },
render: ({ group, title }) => (
<FieldSet>
<FieldLegend>{title}</FieldLegend>
<group.InputField label="Street" name="street" />
<group.InputField label="City" name="city" />
</FieldSet>
),
})
<AddressFields fields="billing" form={form} title="Billing" />
<AddressFields fields="shipping" form={form} title="Shipping" />fieldsis a path of the form ("billing",`rows[${index}]`) or, for a group whose keys sit at different paths, a map of them ({ city: "city", street: "line1" }).- A group reads
fieldsonce, when it mounts. When its path can change, as an array row's index does when a row above it is removed, key the group by that path (key={`rows[${index}]`}) so it remounts on the new one. - A group renders another by passing its own
groupasform. - A field that shows or hides on another's value reads it with
useSelector(group.store, (state) => state.values?.country), as a form does. Keep the?.: a group'svaluesareundefinedwhile the form has nothing at the group's path, such as a removed array row before its group unmounts, whatever their type says. group.AppFieldwith a render function still works for a field that needs its own field API, such as an array'spushValue, or arenderItemthat needs its item's type: a named field, on a group or a form, takes a generic field's items asunknown, wherefield.ComboboxFieldinfers them.- A group has no validators of its own. The form's
schemavalidates its fields at their full paths.
Devtools
Install @tanstack/react-devtools and @tanstack/react-form-devtools
(@zeno-lib/forms lists both as optional peer dependencies), then render the panel
near your app root:
import { TanStackDevtools } from "@tanstack/react-devtools"
import { formDevtoolsPlugin } from "@tanstack/react-form-devtools"
<TanStackDevtools plugins={[formDevtoolsPlugin()]} />Every useForm instance appears in the panel with its live state. You don't need to wrap
anything.