Using the react-hook-form
library simplifies form handling in React by providing a convenient and efficient way to manage form state, validation, and submission, eliminating the need to write extensive custom code.
React Hook Form - performant, flexible and extensible form library
react-hook-form
Installation
npm install react-hook-form
Import useForm
Hook
import { useForm } from 'react-hook-form';
Initialize Form State
const {register, handleSubmit} = useForm();
register
: This function is used to register your form inputs. It returns props to spread onto your input elements.handleSubmit
: This function is used to handle form submission. You pass your submit function to this handler.Form Submission
function handleFormSubmit(formData) {
console.log('Form Data: ', formData);
}
HTML Form
<form onSubmit={handleSubmit(handleFormSubmit)}>
<input type="text" {...register('username')} />
<input type="email" {...register('email')} />
<input type="password" {...register('password')} />
<button type="submit">Submit</button>
</form>
required
<div className="mt-2">
<label htmlFor="username" className="form-lable">Username</label>
<input type="text" {...register('username',{required:true})} id="username" className="form-control"/>
</div>
minLength
<div className="mt-2">
<label htmlFor="username" className="form-lable">Username</label>
<input type="text" {...register('username',{required:true,minLength:4})} id="username" className="form-control"/>
</div>
maxLength
<div className="mt-2">
<label htmlFor="username" className="form-lable">Username</label>
<input type="text" {...register('username',{required:true,maxLength:8})} id="username" className="form-control"/>
</div>
<div className="mb-3">
<label htmlFor="username" className='form-label'>Username</label>
<input type="text" {...register('username',{required:true,minLength:4,maxLength:8})} className='form-control' id="username" />
</div>