Making forms easier with react-hook-form

In this article, we will see how we can improve our developer experience and time while working with forms by using react-hook-form.

There are many libraries that facilitate working with forms making it easier to write and validate inputs

const { register, handleSubmit, watch, formState: { errors } } = useForm();

In order to use it, we have to call useForm hook. This will give properties that can we use in our code.

register will register your input element for validation and management
handleSubmit will handle your form submission
watch will constantly watch an element change
formState will give you the state of the form

<form onSubmit={handleSubmit(onSubmit)}>

handleSubmit will submit your form. Before submitting your form it will check for errors. If errors are found it will not proceed until all of the errors have been resolved.

<input placeholder="Jhon Doe" {...register('name')} />

We have defined the input element and registered it as name for validation.

<input
          placeholder="25"
          {...register('age', { required: true })}
          type="number"
        />

With registering we have also applied validation that this input is required.

<input
          type="number"
          {...register('experience', { min: 4 })}
          placeholder="4"
        />

input will not accept values that are under 4

<input
          type="number"
          {...register('experience', { max: 4 })}
          placeholder="4"
        />

Similarly, input will not accept values above 4

Suppose if you want to limit user for text length, you would do by

<textarea rows="4" cols="20" {...register('bio', {
          maxLength: 200
        })}

It will limit users to a maximum of 200 characters

Ok! Now we know how validation works but what is watch.

watch will constantly check for input values
Suppose if you want to monitor textarea in real-time, you might need to watch it and inform users that they have entered a certain words.

let bio = watch('bio');
  console.log(bio);

  if (bio && bio.includes('ice')) {
    alert('You have written ice');
  }

.includes is a method on string. It will check if characters are involved in string

In order to inform users about the errors, we would have to refer to the errors object.

Let's recall

<div>
        <label htmlFor="bio">Bio</label>
        <br />
        <textarea
          rows="4"
          cols="20"
          {...register('bio', {
            maxLength: 30,
          })}
        />
        {errors.bio && <h4>Your bio have exceeded beyond 30 characters</h4>}
      </div>

If the maximum length of textarea exceeds 30 characters, it will give an error.

I hope you liked this article, if you have any questions/feedback feel free to ask me!

18