zod-auto-form
v0.0.32
Published
Auto-generate typed React forms from Zod schemas
Maintainers
Readme
zod-auto-form
A React library for automatic form generation using Zod schemas.
Features
- 🚀 Automatically generate forms from Zod schemas
- 🧩 Customizable components for each field type
- 🔍 Input validation using Zod
- 🎨 Flexible styling options
- 📱 Responsive form layouts
- 🔄 Support for complex nested objects and arrays
- 👁️ Field visibility rules for conditional rendering
- 🛠️ Field type overrides for custom input components
Installation
npm install zod-auto-form zod
# or
yarn add zod-auto-form zod
# or
pnpm add zod-auto-form zodDefault Components
You can quickly get started with the default shadcn/ui components:
# Using npm
npx shadcn@latest add https://raw.githubusercontent.com/atul7017128880/component-registry/refs/heads/master/public/registry/auto-form-component.json
# Using pnpm
pnpm dlx shadcn@latest add https://raw.githubusercontent.com/atul7017128880/component-registry/refs/heads/master/public/registry/auto-form-component.json
# Using Bun
bunx --bun shadcn@latest add https://raw.githubusercontent.com/atul7017128880/component-registry/refs/heads/master/public/registry/auto-form-component.jsonQuick Start
import { z } from 'zod';
import { AutoForm, AutoFormComponentsProvider } from 'zod-auto-form';
import YourCustomComponents from './your-components';
import { ComponentRegistry } from '../shadcn-ui-components';
// 1. Define your schema with Zod
const userFormSchema = z.object({
name: z.string().min(2, "Name must be at least 2 characters"),
email: z.string().email("Invalid email address"),
age: z.number().min(18, "Must be at least 18 years old"),
isSubscribed: z.boolean().default(false),
});
// 2. Create your form component
function UserForm() {
return (
<AutoFormComponentsProvider components={ComponentRegistry or YourCustomComponents}>
<AutoForm
formSchema={userFormSchema}
onSubmit={(values) => {
console.log(values);
// Handle form submission
}}
onSubmitError={(error, errorMessages, values) => {
console.error('Form validation failed:', errorMessages);
}}
/>
</AutoFormComponentsProvider>
);
}Component Registration
You need to provide your UI components through the AutoFormComponentsProvider:
import { AutoFormComponentsProvider,ComponentRegistry} from 'zod-auto-form';
// Your custom form components that match the expected interfaces fully typed
const myComponents = ComponentRegistry({
Input: MyTextInput,
Select: MySelectComponent,
NumberInput: MyNumberInput,
// ... other component types
});
function App() {
return (
<AutoFormComponentsProvider components={myComponents}>
{/* Your app/forms here */}
</AutoFormComponentsProvider>
);
}Supported Field Types
string- Text inputsnumber- Numeric inputsboolean- Checkboxes and switchesarray- Array fields with add/remove functionalityobject- Nested object fieldsselect- Dropdown select fieldsmulti-select- Multiple selection fieldsdate- Date/time pickerstextarea- Multi-line text inputsswitch- Toggle switchesradio- Radio button groups
Advanced Usage
Field Type Overrides
Override the automatically determined field types:
<AutoForm
formSchema={schema}
fieldTypeOverrides={{
description: {
typeOfField: "textarea",
},
}}
// ...
/>Visibility Rules
Control which fields are displayed based on other field values:
<AutoForm
formSchema={schema}
visibilityRules={[
{
sourceFields: ["age"],
targetField: "address",
when: (values) => values.age > 18,
type: "show",
},
{
sourceFields: ["name"],
targetField: "address.city",
when: (values) => values.name === "John",
type: "show",
},
]}
// ...
/>Grouped Fields
Organize fields into logical groups:
// The library will automatically detect and group fields defined in nested objects
<AutoForm
formSchema={schema}
groupByZodKeys={{
Users: ["age", "name"],
Address: ["address"],
}}
// ...
/>Change Position of Fields
Change the position of fields:
<AutoForm
formSchema={schema}
changePositionOfFields={{
nested: {
age: {
position: 0,
},
name: {
position: 1,
},
address: {
position: 2,
nested: {
city: {
position: 0,
},
street: {
position: 1,
},
},
},
},
}}
// ...
/>API Reference
<AutoForm> Props
| Prop | Type | Description |
|------|------|-------------|
| formSchema | z.ZodSchema | The Zod schema used to generate the form |
| fieldTypeOverrides | object | Override the automatically determined field types |
| changePositionOfFields | object | Change the position of fields |
| groupByZodKeys | object | Group fields by Zod keys |
| visibilityRules | object | Rules for conditionally showing/hiding fields |
| defaultValues | object | Initial values for the form fields |
| formId | string | Optional ID for the form element |
| onSubmit | function | Callback when form is successfully submitted |
| onSubmitError | function | Callback when validation fails on submission |
<AutoFormComponentsProvider> Props
| Prop | Type | Description |
|------|------|-------------|
| components | object | Custom UI components for rendering different field types |
| children | ReactNode | Child components that will use the provided form components |
<ComponentRegistry> Props
| Prop | Type | Description |
|------|------|-------------|
| components | object | Custom UI components for rendering different field types |
My Info
- Name: [@atul-kumar]
- Email: [email protected]
License
MIT
