How to Use react-hook-form with TypeScript

React Hook Form is a library that helps you to simplify form validation. It uses React hooks to inject required validation checks and to bind a form and a submit handler.

Let's create a signup form with React Hook Form and then type it with TypeScript.

Signup Form#

Out form will contain 3 fields:

To connect the form with validation checks we will use useForm hook from the React Hook Form API:

Here, we use register as a value to ref prop on each input. It binds the input with validation.

We need to pass the name attribute as well since register relies on it. Also, the name must be unique for register to work properly.

The handleSubmit function will call the provided callback if validation is successful. In our case, it will call onSubmit callback and log out all the data from the form.

Form Types#

Now let's create a type for form data. Let's call it User:

When type is created we can use it to annotate the form data:

Required Fields#

To make an input required, we can provide register with a settings object. When we specify the required field as true, the validation returns an errors object. We can use this object to access errors on every field in the form:

Custom Validation#

We can also specify a required pattern for each field to perform custom checks:

Sources#