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.
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.
Now let's create a type for form data. Let's call it
When type is created we can use it to annotate the form data:
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:
We can also specify a required pattern for each field to perform custom checks: