react-auto-form-sasangam
Version:
A React component and hook for automatically generating forms from API endpoints
332 lines (267 loc) • 8.09 kB
Markdown
# React Auto Form
A powerful React component and hook for automatically generating forms from API endpoints. This package provides a dynamic form solution that can automatically detect field types, handle validation, and render appropriate form controls based on API response data.
## Features
- 🚀 **Auto-detection**: Automatically detects field types from API data
- 🎨 **Customizable**: Full control over form rendering with custom renderers
- ✅ **Validation**: Built-in validation with custom rules support
- 📱 **Responsive**: Mobile-friendly design with responsive layouts
- 🎯 **TypeScript**: Full TypeScript support with comprehensive type definitions
- 🔧 **Flexible**: Support for nested objects, file uploads, and complex data structures
- 🎨 **Styled**: Beautiful default styling with CSS-in-JS support
## Installation
```bash
npm install react-auto-form
# or
yarn add react-auto-form
# or
pnpm add react-auto-form
```
## Quick Start
```tsx
import React from 'react';
import { AutoForm, useAutoForm } from 'react-auto-form';
function MyForm() {
return (
<AutoForm
endpoint="/api/users"
onSubmit={(data) => console.log('Form submitted:', data)}
/>
);
}
// Or use the hook directly for more control
function CustomForm() {
const {
formData,
formSchema,
isLoading,
errors,
updateField,
handleSubmit
} = useAutoForm('/api/users');
if (isLoading) return <div>Loading...</div>;
return (
<form onSubmit={handleSubmit}>
{/* Your custom form rendering */}
</form>
);
}
```
## API Reference
### AutoForm Component
The main component that automatically renders forms based on API endpoints.
#### Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `endpoint` | `string` | - | API endpoint URL to fetch form schema from |
| `options` | `AutoFormOptions` | `{}` | Configuration options for the form |
| `className` | `string` | `''` | CSS class name for the form container |
| `submitButtonText` | `string` | `'Submit'` | Text for the submit button |
| `resetButtonText` | `string` | `'Reset'` | Text for the reset button |
| `showResetButton` | `boolean` | `true` | Whether to show the reset button |
| `customRenderer` | `function` | - | Custom renderer function for complete form control |
| `onSubmit` | `function` | - | Callback when form is submitted |
| `onReset` | `function` | - | Callback when form is reset |
| `onError` | `function` | - | Callback when an error occurs |
### useAutoForm Hook
A React hook that provides form state management and utilities.
#### Parameters
- `endpoint: string` - API endpoint URL
- `options: AutoFormOptions` - Configuration options
#### Returns
```tsx
{
// Form data and schema
formData: Record<string, any>;
formSchema: Record<string, FieldSchema> | null;
// State
isLoading: boolean;
isSubmitting: boolean;
errors: Record<string, string>;
touched: Record<string, boolean>;
// Form actions
updateField: (fieldName: string, value: any) => void;
handleSubmit: (e?: React.FormEvent) => Promise<any>;
resetForm: () => void;
validateForm: () => boolean;
// Utilities
getFieldProps: (fieldName: string) => FieldProps;
getFormState: () => FormState;
// ... and more
}
```
### AutoFormOptions
```tsx
interface AutoFormOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
initialData?: Record<string, any>;
autoFetch?: boolean;
validationRules?: Record<string, ValidationRules>;
onSubmit?: (data: Record<string, any>) => Promise<void> | void;
onError?: (error: Error) => void;
transformResponse?: (data: any) => Record<string, any>;
transformRequest?: (data: Record<string, any>) => any;
headers?: Record<string, string>;
auth?: {
username: string;
password: string;
};
loginEndpoint?: string;
useCookies?: boolean;
}
```
## Examples
### Basic Usage
```tsx
import { AutoForm } from 'react-auto-form';
function App() {
return (
<AutoForm
endpoint="https://api.example.com/users"
onSubmit={(data) => {
console.log('Form data:', data);
// Handle form submission
}}
/>
);
}
```
### Custom Styling
```tsx
import { AutoForm } from 'react-auto-form';
import './custom-styles.css';
function App() {
return (
<AutoForm
endpoint="/api/contact"
className="my-custom-form"
submitButtonText="Send Message"
resetButtonText="Clear Form"
/>
);
}
```
### Using the Hook
```tsx
import { useAutoForm } from 'react-auto-form';
function CustomForm() {
const {
formData,
formSchema,
isLoading,
errors,
updateField,
handleSubmit,
isFormValid
} = useAutoForm('/api/products', {
method: 'POST',
validationRules: {
name: { required: true, minLength: 3 },
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ }
}
});
if (isLoading) return <div>Loading form...</div>;
return (
<form onSubmit={handleSubmit}>
<div>
<label>Product Name</label>
<input
value={formData.name || ''}
onChange={(e) => updateField('name', e.target.value)}
/>
{errors.name && <span className="error">{errors.name}</span>}
</div>
<button type="submit" disabled={!isFormValid}>
Submit
</button>
</form>
);
}
```
### Custom Renderer
```tsx
import { AutoForm } from 'react-auto-form';
function App() {
const customRenderer = ({ formSchema, formData, updateField, errors }) => (
<div className="custom-form">
{formSchema && Object.entries(formSchema).map(([fieldName, fieldSchema]) => (
<div key={fieldName} className="field-group">
<label>{fieldSchema.label}</label>
<input
type={fieldSchema.type}
value={formData[fieldName] || ''}
onChange={(e) => updateField(fieldName, e.target.value)}
/>
{errors[fieldName] && (
<span className="error">{errors[fieldName]}</span>
)}
</div>
))}
</div>
);
return (
<AutoForm
endpoint="/api/data"
customRenderer={customRenderer}
/>
);
}
```
## Field Types
The package automatically detects and renders appropriate form controls for:
- **Text inputs** (text, email, password, url, tel)
- **Number inputs** (number, range)
- **Date/Time inputs** (date, time, datetime-local)
- **File uploads** (with drag & drop support)
- **Text areas** (for long text content)
- **Select dropdowns** (single and multiple selection)
- **Checkboxes** (boolean values)
- **Nested objects** (with recursive field rendering)
## Styling
The package includes comprehensive CSS styles that you can customize. The styles are automatically included when you import the package.
### CSS Classes
- `.auto-form-container` - Main form container
- `.form-field` - Individual field wrapper
- `.form-label` - Field labels
- `.form-input` - Input elements
- `.form-error` - Error messages
- `.form-actions` - Submit/reset buttons container
### Custom CSS
```css
.my-custom-form {
background: #f8f9fa;
border-radius: 12px;
padding: 24px;
}
.my-custom-form .form-field {
margin-bottom: 24px;
}
.my-custom-form .form-input {
border: 2px solid #e1e5e9;
border-radius: 8px;
padding: 12px;
}
```
## TypeScript Support
The package is written in TypeScript and provides full type definitions:
```tsx
import { AutoForm, useAutoForm, FieldSchema, AutoFormOptions } from 'react-auto-form';
// All types are available for use in your code
const options: AutoFormOptions = {
method: 'POST',
validationRules: {
email: { required: true, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ }
}
};
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
MIT © [Your Name](https://github.com/yourusername)
## Changelog
### 1.0.0
- Initial release
- Auto-form generation from API endpoints
- TypeScript support
- Custom validation rules
- File upload support
- Responsive design