@7span/react-form
v0.1.0
Published
Dynamic forms for React - Generate forms from JSON field definitions.
Downloads
104
Readme
@7span/react-form
Dynamic forms for React - Generate forms from JSON field definitions.
Installation
npm install @7span/react-formQuick Start
import {
ReactForm,
ReactFormFields,
ReactFormField,
ReactFormCreate,
ReactFormUpdate,
} from "@7span/react-form";
function App() {
const fields = ["name", { name: "email", value: "[email protected]" }];
const create = (context) => {
return Promise.resolve({ values: context.values });
};
const update = (itemId, context) => {
return Promise.resolve({ values: context.values });
};
return (
<ReactForm fields={fields} create={create} update={update}>
{({ context }) => (
<>
<ReactFormFields>
{({ values }) => (
<>
<ReactFormField name="name">
{({ field, label }) => (
<>
<label>{label}</label>
<input {...field} />
</>
)}
</ReactFormField>
<ReactFormField name="email">
{({ field, label }) => (
<>
<label>{label}</label>
<input type="email" {...field} />
</>
)}
</ReactFormField>
</>
)}
</ReactFormFields>
<ReactFormCreate />
<ReactFormUpdate />
</>
)}
</ReactForm>
);
}Components
ReactForm- Root form componentReactFormFields- Field container componentReactFormField- Individual field wrapperReactFormCreate- Create button componentReactFormUpdate- Update button componentReactFormDelete- Delete button componentReactFormArchive- Archive button componentReactFormUnarchive- Unarchive button componentReactFormError- Error display component
Features
- Dynamic form generation from field definitions
- CRUD operations (Create, Read, Update, Delete, Archive, Unarchive)
- State management using React Context
- Field configuration (strings or objects)
- Error handling with customizable error adapters
- Granular components for flexible composition
- Schema Support - Accepts custom validation schemas (Zod, Yup, or any validation library)
- Custom Validation - Provide your own
validateSchemafunction - Field Extraction - Custom
schemaToFieldsfunction to extract fields from schemas - Field-level and form-level validation errors
- Built-in error management utilities
Validation
The library supports validation through custom validateSchema and schemaToFields functions. You can use any validation library (Zod, Yup, or custom). Install the validation library of your choice:
# For Zod (example)
npm install zod@^4.2.1
# For Yup (example)
npm install yup@^1.7.1Basic Usage with Validation
import { ReactForm, ReactFormProvider, ReactFormField } from "@7span/react-form";
import { z } from "zod";
const schema = z.object({
name: z.string().min(2, "Name must be at least 2 characters"),
email: z.string().email("Invalid email address"),
});
// Custom validation function
const validateSchema = async (schema, values) => {
const result = schema.safeParse(values);
if (result.success) {
return { success: true, errors: {} };
}
const fieldErrors = result.error.issues.reduce((acc, issue) => {
const field = issue.path[0]; // "id", "email", etc.
if (!field) return acc;
acc[field] = {
message: issue.message, // ← EXACT message from schema
};
return acc;
}, {});
return { success: false, errors: fieldErrors };
};
// Custom schema to fields converter
const schemaToFields = (schema) => {
if (schema && schema.shape && typeof schema.shape === 'object') {
return Object.keys(schema.shape).map((key) => {
const defaultValue = schema.shape[key]._def.defaultValue();
const label = schema.shape[key]._def.description;
return {
name: key,
label: label || key.charAt(0).toUpperCase() + key.slice(1),
value: defaultValue,
};
});
}
return [];
};
function MyForm() {
return (
<ReactFormProvider
schemaToFields={schemaToFields}
validateSchema={validateSchema}
>
<ReactForm
fields={["name", "email"]}
schema={schema}
create={async (context) => {
console.log("Valid data:", context.values);
}}
>
{({ context }) => (
<>
<ReactFormField name="name">
{({ field, label, error }) => (
<>
<label>{label}</label>
<input {...field} />
{error && <span className="error">{error.message}</span>}
</>
)}
</ReactFormField>
<ReactFormField name="email">
{({ field, label, error }) => (
<>
<label>{label}</label>
<input type="email" {...field} />
{error && <span className="error">{error.message}</span>}
</>
)}
</ReactFormField>
</>
)}
</ReactForm>
</ReactFormProvider>
);
}See VALIDATION.md for detailed validation documentation.
Exports
The package exports all components, context utilities, and error management functions:
import {
// Components
ReactForm,
ReactFormFields,
ReactFormField,
ReactFormCreate,
ReactFormUpdate,
ReactFormDelete,
ReactFormArchive,
ReactFormUnarchive,
ReactFormError,
// Context & Providers
ReactFormProvider,
useReactForm,
// Utilities
attrSerializer,
// Error Management
getFieldError,
setFieldError,
setFieldErrors,
clearAllErrors,
clearFieldError,
} from "@7span/react-form";Documentation
See the documentation for more details.
