1.1.7 • Published 4 months ago
rc-simple-hook-form v1.1.7
useForm Hook
Overview
useForm
is a powerful and flexible React hook for managing form state, validation, and interactions. It provides a comprehensive solution for handling form inputs with advanced features like state management, validation, and form-level controls.
Installation
npm install rc-simple-hook-form
or
yarn add rc-simple-hook-form
Controller
Component
The Controller
component provides an advanced way to render and control form fields with more flexibility.
Controller Props
interface ControllerProps {
name: string;
type: InputType;
control: ReturnType<typeof useForm>["control"];
initialValue?: unknown;
rules?: ValidationFields;
disabled?: boolean;
runValidationWhenChangesIn?: string[];
ref?: React.MutableRefObject<EventElement>;
radioFieldValue?: string;
checkboxFieldValue?: string;
render: (arg: RenderProp) => React.JSX.Element;
}
Render Prop Details
The render
prop receives two arguments:
field
Object
value
: Current field valuechecked
: Checkbox/radio checked statemultiple
: Select multiple statedisabled
: Field disabled statename
: Field nametype
: Input typeonBlur
: Blur event handleronChange
: Change event handleronFocus
: Focus event handlerref
: Reference to the input element
fieldState
Object
isTouched
: Whether the field has been touchedisDirty
: Whether the field value has changed from initialinvalid
: Whether the field has validation errorsisActive
: Whether the field is currently focusederror
: Validation error messages
Basic Usage
const MyForm = () => {
const { register, handleSubmit, formState } = useForm({
initialState: { username: '', email: '' }
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username', { required: true })} />
<input {...register('email', { required: true, email: true })} />
<button type="submit">Submit</button>
</form>
);
};
Controller Example
const MyForm = () => {
const { control } = useForm();
return (
<form>
<Controller
name="username"
type="text"
control={control}
rules={{ required: true, minLength: 3 }}
render={({ field, fieldState }) => (
<div>
<input {...field} />
{fieldState.invalid && <span>Invalid input</span>}
</div>
)}
/>
</form>
);
};
Advanced Example with Controller
const ComplexForm = () => {
const { control, handleSubmit } = useForm({
initialState: {
username: '',
termsAccepted: false
}
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="username"
type="text"
control={control}
rules={{
required: 'Username is required',
minLength: { value: 3, message: 'Min 3 characters' }
}}
render={({ field, fieldState }) => (
<div>
<input {...field} />
{fieldState.invalid && <span>{fieldState.error}</span>}
</div>
)}
/>
<Controller
name="termsAccepted"
type="checkbox"
control={control}
rules={{ required: true }}
render={({ field }) => (
<div>
<input
type="checkbox"
checked={field.checked}
onChange={field.onChange}
/>
<label>Accept Terms</label>
</div>
)}
/>
</form>
);
};
Additional Notes on Controller
- Provides more granular control over form field rendering
- Supports complex validation scenarios
- Allows custom rendering of form fields
- Integrates seamlessly with the
useForm
hook
API Reference
Parameters
UseFormParam<T>
initialState
: Optional initial form values of typeT
Return Object
The useForm
hook returns an object with the following properties:
formState
An object containing form-level state:
values
: Current form valuesactive
: Fields currently in focustouched
: Fields that have been interacted witherrors
: Validation errorsinvalid
: Boolean indicating if form is invalidfieldPristine
: Pristine state of individual fieldsformPristine
: Overall form pristine state
control
Methods
getFormState()
: Returns current form stateregister(name, type, extraProps)
: Registers an input fieldresetForm()
: Resets entire form to initial stateresetField(name)
: Resets specific field to initial valuesetField(name, value, options)
: Manually set field value
handleSubmit(callback)
Wraps form submission with validation check
register
Method Details
register(
name: string,
type: InputType,
extra?: {
radioFieldValue?: any,
checkboxFieldValue?: any,
ref?: React.Ref,
disabled?: boolean,
runValidationWhenChangeIn?: string[],
handleOnChange?: (e) => void,
handleOnBlur?: (e) => void,
handleOnFocus?: (e) => void,
// Validation rules
required?: boolean | string,
minLength?: { value: number, message?: string },
maxLength?: { value: number, message?: string },
// Custom validation functions can be added
}
)
Validation Features
- Supports multiple validation types
- Custom error messages
- Linked validation between fields
- Validation runs on touched fields
- Supports various input types (text, radio, checkbox, select)
Advanced Example
const MyComplexForm = () => {
const {
register,
formState: { errors, invalid },
setField,
resetForm
} = useForm({
initialState: {
username: '',
email: '',
termsAccepted: false
}
});
const validatePassword = (value) => {
return value.length >= 8 ? VALID : 'Password too short';
};
return (
<form>
<input
{...register('username', {
required: 'Username is required',
minLength: { value: 3, message: 'Min 3 characters' }
})}
/>
{errors.username && <span>{errors.username[0]}</span>}
<input
{...register('password', {
validate: validatePassword
})}
/>
<button disabled={invalid}>Submit</button>
</form>
);
};
Performance Considerations
- Uses
useMemo
anduseCallback
for optimized rendering - Batched updates with
unstable_batchedUpdates
- Minimal re-renders through efficient state management
TypeScript Support
Full TypeScript support with generic type inference for form values.
Contributing
Contributions welcome! Please submit issues and pull requests on GitHub.