Skip to Content
ZenoZENO

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/forms

create-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:

Subscribe to our newsletter
Monthly digest of new fields, examples, and releases.
"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. name props autocomplete against defaultValues, and value types 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 calls form.handleSubmit() on submit. A SubmitButton inside 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 in defaultValues, the only way to tell the form which empty value you want.
  • Anything you put in defaultValues always wins on conflict; the schema only fills the keys you leave out.
  • Nested z.object(...) follows the same rules, and useForm deep-merges a partial nested object from defaultValues into 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:

create-form.tsx
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 as undefined keeps 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's children) fails the type check.
  • Defaults belong to the component they are keyed by. The fields built on InputField, such as EmailField and MoneyField, don't take InputField's.
  • The defaults apply however the component renders: from useForm's form, a section's form or a group's group, from useAppFields, or as field.MoneyField inside form.AppField.
  • The field files stay as the registry ships them. The create-form item ships create-form.tsx with them, though, so when you re-add it to update the fields, carry your defaultProps over to the new file.
  • A default is a fixed value. One that depends on another prop, such as a max that follows scale, 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 type form. Pass a value of the form's type, as above, or spread the formOptions your useForm call shares.
  • A form with other values fails the type check where the parent renders the section.
  • The section's form carries the same typed fields as useForm's, default props included. useAppFields(form) gives them to a form typed some other way.
  • render runs inside a component, so it can call hooks. Keep it an arrow function, because Biome's hook rule doesn't recognize a render() {} method as a component.
  • For a group of fields that several forms reuse at different paths, such as an address under both billing and shipping, use withFieldGroup.

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" />
  • fields is 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 fields once, 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 group as form.
  • 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's values are undefined while the form has nothing at the group's path, such as a removed array row before its group unmounts, whatever their type says.
  • group.AppField with a render function still works for a field that needs its own field API, such as an array's pushValue, or a renderItem that needs its item's type: a named field, on a group or a form, takes a generic field's items as unknown, where field.ComboboxField infers them.
  • A group has no validators of its own. The form's schema validates 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.