react-elite-form
v0.4.1
Published
A powerful, type-safe React form management library with built-in validation, nested object support, and zero dependencies.
Readme
React Elite Form
A powerful, type-safe React form management library with built-in validation, nested object support, and zero dependencies.
Features
- ✅ Type-safe - Full TypeScript support with intelligent type inference
- ✅ Zero dependencies - Completely standalone with no external runtime dependencies
- ✅ Nested objects & arrays - Handle complex form structures with ease
- ✅ Built-in validation - Real-time validation on change, blur, or submit
- ✅ Error handling - Comprehensive error state management
- ✅ Dirty & touched state tracking - Track which fields have been modified and touched
- ✅ Form submission handling - Built-in form submission with validation
- ✅ Performance optimized - Minimal re-renders with targeted updates
- ✅ Auto cleanup - Optional automatic field unregistration
Installation
npm install react-elite-formyarn add react-elite-formpnpm add react-elite-formQuick Start
import { useForm } from "react-elite-form";
interface User {
name: string;
email: string;
age: number;
}
function MyForm() {
const { register, registerForm, state, errors } = useForm<User>({
name: "",
email: "",
age: 0,
});
const handleSuccess = () => {
console.log("Form submitted successfully!", state);
};
const handleError = () => {
console.log("Form has validation errors");
};
return (
<form {...registerForm(handleSuccess, handleError)}>
<input
{...register("name", {
type: "text",
validation: (value) => (value.length < 2 ? "Name must be at least 2 characters" : undefined),
})}
placeholder="Name"
/>
{errors.name && <span>{errors.name}</span>}
<input {...register("email", { type: "text" })} placeholder="Email" />
<input {...register("age", { type: "number" })} placeholder="Age" />
<button type="submit">Submit</button>
<pre>{JSON.stringify(state, null, 2)}</pre>
</form>
);
}Advanced Usage
Form Options
interface User {
name: string;
email: string;
}
function FormWithOptions() {
const { register, state, errors } = useForm<User>(
{
name: "",
email: "",
},
{
clearErrorOnChange: true, // Clear field errors when user starts typing
autoUnregister: true, // Automatically remove unused field data
}
);
return (
<form>
<input {...register("name", { type: "text" })} placeholder="Name" />
<input {...register("email", { type: "text" })} placeholder="Email" />
</form>
);
}Nested Objects
interface User {
name: string;
address: {
street: string;
city: string;
zip: number;
};
}
function NestedForm() {
const { register, updateField } = useForm<User>({
name: "",
address: { street: "", city: "", zip: 0 },
});
return (
<form>
<input {...register("name", { type: "text" })} />
<input {...register("address.street", { type: "text" })} />
<input {...register("address.city", { type: "text" })} />
<input {...register("address.zip", { type: "number" })} />
</form>
);
}Radio Buttons & Checkboxes
interface Preferences {
theme: "light" | "dark" | "auto";
notifications: boolean;
}
function PreferencesForm() {
const { register } = useForm<Preferences>({
theme: "light",
notifications: false,
});
return (
<form>
{/* Radio buttons */}
<div>
<label>
<input {...register("theme", { type: "radio", label: "light" })} />
Light
</label>
<label>
<input {...register("theme", { type: "radio", label: "dark" })} />
Dark
</label>
<label>
<input {...register("theme", { type: "radio", label: "auto" })} />
Auto
</label>
</div>
{/* Checkbox */}
<label>
<input {...register("notifications", { type: "checkbox", label: "enabled" })} />
Enable notifications
</label>
</form>
);
}Custom Select & Validation
interface FormData {
category: { id: number; name: string } | null;
email: string;
}
function CustomForm() {
const { register, updateField } = useForm<FormData>({
category: null,
email: "",
});
const emailValidation = (value: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return !emailRegex.test(value) ? "Please enter a valid email" : undefined;
};
return (
<form>
<select
{...register("category", { type: "select" })}
onChange={(e) => updateField("category", e.target.value ? { id: 1, name: e.target.value } : null)}
>
<option value="">Select category</option>
<option value="tech">Technology</option>
<option value="design">Design</option>
</select>
<input
{...register("email", {
type: "text",
validation: emailValidation,
validationType: "blur", // Validate on blur instead of submit
})}
placeholder="Email"
/>
</form>
);
}API Reference
useForm<T>(initialValue: T, options?: FormOptions)
The main hook for form management.
Parameters
initialValue: T- Initial form stateoptions?: FormOptions- Configuration options
FormOptions
clearErrorOnChange?: boolean- Clear field errors when user starts typing (default:false)autoUnregister?: boolean- Automatically remove unused field data (default:false)
Returns
state: T- Current form stateregister- Function to register form fieldsregisterForm- Function to register form submission handlingupdateField- Function to programmatically update a fieldupdateFields- Function to update multiple fields at onceerrors- Current validation errorsclearFieldError- Clear error for a specific fieldclearFieldsErrors- Clear errors for multiple fieldsresetErrors- Clear all errorsisFormDirty- Boolean indicating if form has been modifiedisFormWithError- Boolean indicating if form has validation errorsresetDirty- Reset dirty statevalidate- Trigger form validationisFormSubmitted- Boolean indicating if form has been submitted
register(fieldName, options)
Register a form field with validation and type information.
Options
type: 'text' | 'number' | 'radio' | 'checkbox' | 'select' | 'custom'- Input typevalidation?: (value, formState) => string | undefined- Validation functionvalidationType?: 'change' | 'blur' | 'submit'- When to trigger validation (default: 'submit')autoUnregister?: boolean- Whether to automatically unregister this fieldlabel?: string- Label for radio/checkbox inputs
Returns
Appropriate props for the input type:
- Text/Number:
{ value, name, error, touched, onChange, onBlur? } - Radio/Checkbox:
{ value, name, checked, error, touched, onChange } - Select/Custom:
{ value, name, error, touched, onChange }
registerForm(onSuccess?, onError?)
Register form submission handling with automatic validation.
Parameters
onSuccess?: () => void- Callback when form validation passesonError?: () => void- Callback when form validation fails
Returns
ref: React.RefObject<HTMLFormElement>- Form refonSubmit: (event: FormEvent) => void- Form submit handler
TypeScript Support
React Elite Form provides full TypeScript support with intelligent type inference:
interface User {
profile: {
name: string;
tags: string[];
};
}
const { register } = useForm<User>({
profile: { name: "", tags: [] },
});
// ✅ Type-safe field registration
register("profile.name", { type: "text" });
// ❌ TypeScript error - invalid field path
register("profile.invalid", { type: "text" });License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
