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

Steps For react-hook-form

  1. Installation

    npm install react-hook-form
    
  2. Import useForm Hook

    import { useForm } from 'react-hook-form';
    
  3. Initialize Form State

    const {register, handleSubmit} = useForm();
    
  4. Form Submission

    function handleFormSubmit(formData) {
      console.log('Form Data: ', formData);
    }
    
  5. 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>
    

Form Validation

1. 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>

2. 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>

3. 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>

Usage

<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>

Error display