tanstack-form
Build forms using TanStack Form with the project's useAppForm composition, composable field components, Zod validation schemas, FormFieldWrapper error tracking, and form.AppField vs form.Field patterns. Use when creating new forms, adding form fields, writing form validation, or working with TanStack Form in this project.
- License 许可
- MIT
- 最近更新
- 2026-10-23
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- tanstack-form
- description
- Build forms using TanStack Form with the project's useAppForm composition, composable field components, Zod validation schemas, FormFieldWrapper error tracking, and form.AppField vs form.Field patterns. Use when creating new forms, adding form fields, writing form validation, or working with TanStack Form in this project.
- user-invocable
- false
02 资源文件 1
- 参考文档REFERENCE.md23.7 KB
03 SKILL.md 正文
TanStack Form — Project Composition Guide
Architecture Layers
This project wraps TanStack Form into a 4-layer composition:
- Context —
createFormHookContexts()→fieldContext,formContext,useFieldContext - Field Components — composable components that consume
useFieldContext()to read field state/errors - Hook Factory —
createFormHook()→useAppForm,withForm,withFieldGroup - Form Instances —
useAppForm({ validators, defaultValues, onSubmit })
See REFERENCE.md for full file paths, all registered field components, and advanced patterns.
Quick Start — Creating a Form
Key patterns:
form.AppFieldprovides pre-registered field components (field.InputField,field.FormFieldWrapper, etc.)form.Fieldprovides raw field state for custom rendering, array fields, or conditional logicform.Subscribeobserves form state reactively (submit button, global errors)- Zod schema passed to
validators.onSubmit(not a resolver) FormFieldWrapperis a registered field component — use viafield.FormFieldWrapperinsideform.AppField, not as a standalone importFormFieldWrapperreadsuseFieldContext()→field.state.meta.errors→getFieldErrorMessage()and renders label + input + error message using project'sField,FieldLabel,FieldErrorUI components- For API error mapping, use
formApi.setErrorMap()in mutationonError - For focusing first invalid field on submit, use
focusFirstError()inonSubmitInvalid
// 1. Define schema (src/components/YourForm/schemas.ts)
import { z } from 'zod';
export const yourSchema = z.object({
name: z.string().min(1, {
error() {
return 'This field is required';
},
}),
email: z.email({
error(iss) {
if (!iss.input) {
return 'This field is required';
}
return 'Invalid email';
},
}),
});
// 2. Create form instance in your component
import { focusFirstError } from '@/lib/utils/focusFirstError';
import { useAppForm } from '@/components/Form';
const form = useAppForm({
defaultValues: { name: '', email: '' },
validators: { onSubmit: yourSchema },
onSubmit({ value }) {
/* handle submit */
},
onSubmitInvalid({ formApi }) {
focusFirstError('#your-form', formApi.state.errorMap.onSubmit);
},
});
// 3. Render with form.AppField + field.FormFieldWrapper
<form
id="your-form"
noValidate={true}
onSubmit={(e) => {
e.preventDefault();
form.handleSubmit();
}}
>
<FieldSet>
<FieldGroup>
<form.AppField
name="name"
children={(field) => {
return (
<field.FormFieldWrapper label="Name">
<field.InputField placeholder="Enter name" />
</field.FormFieldWrapper>
);
}}
/>
<form.AppField
name="email"
children={(field) => {
return (
<field.FormFieldWrapper label="Email">
<field.InputField placeholder="Enter email" type="email" />
</field.FormFieldWrapper>
);
}}
/>
<Field>
<form.Subscribe
selector={(state) => {
return [state.canSubmit, state.isSubmitting];
}}
children={([canSubmit, isSubmitting]) => {
return (
<Button type="submit" disabled={!canSubmit} isLoading={isSubmitting}>
Submit
</Button>
);
}}
/>
</Field>
</FieldGroup>
</FieldSet>
</form>
form.AppField vs form.Field
form.AppField |
form.Field |
|
|---|---|---|
| Provides | field.InputField, field.FormFieldWrapper, field.PasswordInputField |
Raw field.state, field.handleChange only |
| Use when | Using a registered field component | Custom rendering, array fields, conditional logic |
| Error tracking | Via field.FormFieldWrapper + useFieldContext |
Manual via field.state.meta.errors |
Rule: Use form.AppField for standard fields. Use form.Field for arrays (mode="array"), custom UI, or reading field values without a registered component.
Choosing form controls:
- Text input ->
field.InputField - Password ->
field.PasswordInputField(has built-in show/hide toggle) - Other controls (Textarea, Switch, Checkbox, RadioGroup, etc.) -> use
form.Fieldwith raw rendering
FormFieldWrapper — Error Tracking
FormFieldWrapper is a registered field component. Access it via field.FormFieldWrapper inside form.AppField. It:
- Calls
useFieldContext()to access field errors - Extracts the first error string via
getFieldErrorMessage(field.state.meta.errors) - Generates a unique ID via
${field.name}${field.form.formId} - Renders using project UI components:
Field(wrapper withdata-invalid),FieldLabel, andFieldError
Props:
label— label text (rendersFieldLabel); if omitted, no label is renderedlabelClassName— CSS class for the label elementclassName— wrapper CSS classchildren— the field input component(s)
Layout Helpers
Use the project's existing UI Field layout components for form structure:
FieldSet— wraps a form section (<fieldset>)FieldGroup— groups fields together with consistent gapFieldLegend— section legend/titleFieldSeparator— visual separator between field groupsFieldDescription— helper text below fields
Import from @/components/ui/Field.
Workflow Checklist
- [ ] Define Zod schema with custom error messages
- [ ] Call
useAppForm()withdefaultValues,validators: { onSubmit: schema }, andonSubmit - [ ] Optionally add
onSubmitInvalidwithfocusFirstError()for accessibility - [ ] Wrap
<form>element withnoValidate,e.preventDefault()+form.handleSubmit() - [ ] Use
FieldSet+FieldGroupfor layout structure - [ ] Use
form.AppField+field.FormFieldWrapper+field.<Component>for each field - [ ] Use
form.Fieldonly for custom/array/conditional fields - [ ] Use
form.Subscribefor submit button state (canSubmit,isSubmitting)
Advanced
See REFERENCE.md for:
- All registered field components and their props
withForm/withFieldGroupcompositionform.Subscribefor reactive state- Array field patterns (editable tables)
- Custom field component creation guide
- API error handling with
formApi.setErrorMap()
04 同仓库更多 Skills
web-security
Enforce web security and avoid security vulnerabilities.
typescript
Write clean, efficient TypeScript code that follows project conventions and advanced type patterns. Use when writing or reviewing TypeScript code, defining types, creating generics, handling errors, or working with React components, Zod schemas, and TanStack libraries.
tanstack-router
TanStack Router patterns for this repo — file-based routing, auth guards, search params, data loading, TanStack Query integration, navigation, and code splitting. Use when creating routes, adding pages, implementing auth flows, working with search/path params, or integrating loaders with TanStack Query.
tanstack-query
TanStack Query patterns for this repo — queryOptions/mutationOptions factories, query key hierarchies, service layer integration, optimistic updates, Suspense usage, error handling, and TanStack Router data loading. Use when creating queries, mutations, API services, query keys, cache invalidation, optimistic updates, or integrating data fetching with routes.
tanstack-form
Build forms using TanStack Form with the project's useAppForm composition, composable field components, Zod validation schemas, FormFieldWrapper error tracking, and form.AppField vs form.Field patterns. Use when creating new forms, adding form fields, writing form validation, or working with TanStack Form in this project.
react
Build clean, modern React components that apply common best practices and avoid common pitfalls like unnecessary state management or useEffect usage.