DEV Community

Steven Frasica
Steven Frasica

Posted on

Intro to React Hook Form

A quick way to render your form and get some user input is to incorporate the React Hook Form in your next app. Forms have always seemed to have many moving parts to me, but using React Hook Form simplified the process.

To get started, enter this into the command line -
npm install react-hook-form

Once you've done that, write this line at the top of your Form.js file -
import {useForm} from 'react-hook-form'

This imports the function useForm().
Next, we will focus on three variables that useForm() returns: register, handleSubmit, and errors.

It will look like this:
useForm() syntax

Now we'll set up a basic form before adding in the variables from useForm().

Alt Text

The register variable will handle tracking changes on the input fields of your form. Pass in {register} as the value for the ref property of the input, like so.

Alt Text

The form needs an onSubmit property so we can send the data from the form. The value of onSubmit will be handleSubmit which will take a callback function as its argument.

For demo purposes, we will console log our form data to ensure we are getting it when we click submit.

Alt Text

In your browser, open up the console, fill out the form, and click submit. You should see an object with the form data in the console. At this point, temporarily remove errors as one of the variables retrieved from useForm(), otherwise it will error out.

Alt Text

Validations

The React Hook Form makes it quick and simple to implement validation in your forms. You can include errors again as one of the variables retrieved from calling useForm(). In your register value, pass in an object containing key/value pairs with proper validations.

We want to ensure a user types in a password, and that it is a sufficient length.

Alt Text

For the user to know the requirements for the password, we need to notify them using errors.

Alt Text

Your form will display an error message if a password has not been entered or if it was too short.

Alt Text

There's much more to React Hook Form and I encourage using the resources below!

Resources

Here are the resources I used to learn about React Hook Form.

Video tutorial

React-hook-form

Discussion (0)