Installing Hook Easy Form only takes a single command and you're ready to roll.
npm install hook-easy-form
Create an array with full description for your form, or you can use ourĀ Constructor for it.
export const form = [
{
name: "name",
value: '',
required: true,
options: {
type: "text"
},
validate: {}
},
{
name: "email",
value: '',
required: true,
options: {
type: "email"
},
validate: {}
},
{
name: "age",
value: '',
required: true,
options: {
type: "number"
},
validate: {}
},
];Pass your form which you generate on step 2, to the hook, and now you can use it.
import React from 'react';
import { form } from './form';
const Component = () => {
const {
formArray, updateEvent, resetEvent, disabled, valid, runValidate, submitEvent,
} = easyHook({ initialForm: form });
const onSubmit = submitEvent((v) => console.log(v));
return (
<form onSubmit={onSubmit}>
{formArray.map((el) => (
<div key={el.name}>
<input
name={el.name}
type={el.options.type}
value={el.value}
onChange={updateEvent}
onBlur={runValidate}
/>
</div>
))}
<button type="submit" disabled={disabled || !valid}>Submit</button>
<button type="button" onClick={resetEvent} disabled={disabled || !valid}>Reset</button>
</form>
);
};