UNPKG

zod-auto-form

Version:

Auto-generate typed React forms from Zod schemas

246 lines (199 loc) 6.27 kB
# 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 ```bash npm install zod-auto-form zod # or yarn add zod-auto-form zod # or pnpm add zod-auto-form zod ``` ## Default Components You can quickly get started with the default shadcn/ui components: ```bash # 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.json ``` ## Quick Start ```tsx 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`: ```tsx 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 inputs - `number` - Numeric inputs - `boolean` - Checkboxes and switches - `array` - Array fields with add/remove functionality - `object` - Nested object fields - `select` - Dropdown select fields - `multi-select` - Multiple selection fields - `date` - Date/time pickers - `textarea` - Multi-line text inputs - `switch` - Toggle switches - `radio` - Radio button groups ## Advanced Usage ### Field Type Overrides Override the automatically determined field types: ```tsx <AutoForm formSchema={schema} fieldTypeOverrides={{ description: { typeOfField: "textarea", }, }} // ... /> ``` ### Visibility Rules Control which fields are displayed based on other field values: ```tsx <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: ```tsx // 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: ```tsx <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 <!-- atul kumar awsatul7@gmail.com --> - Name: [@atul-kumar] - Email: [awsatul7@gmail.com](mailto:awsatul7@gmail.com) ## License MIT