React-hook-form Guide with examples

Spread the love

Have you ever tackled a project that required you to create a form? I am almost sure that the answer is affirmative, given how common forms are when creating user interfaces. However, any front-end developer knows that whereas some forms are simple, others can be complex. The huge size could see you have to work on the same form for hours, if not days. Fortunately, that doesn’t have to be the case if you embrace React-hook forms.

Whether you want to hide or show toggles, it could be a breeze if you use them. They also simplify field interactions, serializing the fields, validation, and error handling. You are most likely smiling, having discovered such a fantastic programming hack. However, it isn’t adequate to go by because you also need to know how to handle a React-hook-form.

Read this React-hook-form guide to learn more about this amazing trick. The piece also includes examples to help you understand fast and clearly. So, without further ado, let’s delve into this React-hook-form guide with examples.

Introduction to a React Hook Form

React Hook Form is a library suitable for validation and managing form states. It comes in handy when developing React Native mobile apps and a React web-based application. Its popularity has snowballed due to how it reduces the amount of code one needs to write to create a form using React.

It also marks the end of any unnecessary re-render of a form component. That’s because it doesn’t use React State, a common practice of implementing form management among other similar libraries. On the contrary, it controls its form inputs using ref, thus resolving the issue of re-rendering forms unnecessarily.

Features of React Hook Form

Besides excellent efficiency, React Hook Form has several features that make it stand out among other React form libraries. They include;

  • It is lightweight hence doesn’t overwhelm an application with bulky code
  • It is compatible with third-party user interface libraries
  • Its compatibility with HTML form validation
  • Third-party form validation support
  • An excellent balance of developer experience and user experience to ensure both parties enjoy using it
  • Fantastic performance
  • Zero dependency

People often compare React Hook Form with Formik, which is also quite popular among React Form libraries. Let’s look at how these two libraries differ;

  • The boiler code in React Hook Form is less than that in Formic
  • They both have methods they apply when improving the form state’s performance but React Hook Form is uncontrolled, whereas Formik is controlled
  • Integration with third-party UI libraries is always seamless and straightforward
  • The form component renders relatively less in React Hook Form than in Formik
  • The bundle size is also small, having been gzipped and minified up to 8.6 kB

How to Install React Hook Form

To install React Hook Form, open your terminal. Use the Create React APP command to create a new app as follows;

  • npx create-react-app my-react-hook-form

Use the cd command to navigate the project’s directory created in the above step.

  • cd my-react-hook-form

After that, install React Hook Form in your new app using either of the two commands

  1. npm install react-hook-form
  2. yarn add react-hook-form

If you follow the guide to the letter, the steps will install that package, and once complete, you can start using React Hook Form as follows;

How to Use React Hook Form

To understand this section of the React-hook-form guide well, we will incorporate an example of creating a simple form using this package.

  1. The first step is importing the useForm hook form react-hook-form

import { useForm } from “react-hook-form”;

 

  1. Once you import the Hook, use it inside your component as follows

const { register, handleSubmit } = useForm();

This React hook returns an object with several properties, but we only need handleSubmit and register in this case. As the name suggests, the register is a method that facilitates the registration of input fields into the React Hook Form. By doing that, you avail it for validation and tracking its value’s changes.

So, the registration of input requires you to pass the register method into the corresponding input field as follows;

 

<input type=”text” name=”Surname” {…register(‘Surname’)} />

Note the spread operator syntax responsible for enabling the strict type-checking feature.

If you are using a version older than the v7, you will notice the ref attribute since its register method is as follows

 

<input type=”text” name=”Surname” ref={register} />

 

Don’t forget to include the name prop before the input component. Additionally, no input component can have the same value as another hence the need for uniqueness in this case.

On the other hand, handleSubmit is the method that facilitates form submission. The developer has to pass the method as a value to the prop onSubmit, and the respective component, which is the form.

The arguments of this method could be a pair of functions. One can handle the situation following a successful validation whereas the other can be appropriate after an unsuccessful validation.

const onFormSubmit  = data => console.log(data);

 

const onErrors = errors => console.error(errors);

 

<form onSubmit={handleSubmit(onFormSubmit, onErrors)}>

{/* … */}

</form>

That’s a summary of the basic use of the useForm React Hook. Here’s a complete code showing how to use React Hook Form

import React from “react”;

import { useForm } from “react-hook-form”;

 

const RegisterForm = () => {

const { register, handleSubmit } = useForm();

const handleRegistration = (data) => console.log(data);

 

return (

<form onSubmit={handleSubmit(handleRegistration)}>

<div>

<label>User Name</label>

<input name=”name” {…register(‘name’)} />

</div>

<div>

<label>Email Address</label>

<input type=”email” name=”email” {…register(’email’)} />

</div>

<div>

<label>Password</label>

<input type=”password” name=”password” {…register(‘password’)}   />

</div>

<button>Register</button>

</form>

);

};

export default RegisterForm;

Thanks to the useForm hook, there was no need to import components to track input values. Consequently, the code becomes relatively easy to maintain since it is clean. The developer also doesn’t need to pass common props such as value and onChange to every input. After all, using the React hook translates to an uncontrolled form.

How to Validate Forms Using React Hook Form

You don’t want users to enter all sorts of data, including irrelevant and incorrect data. That’s where form validation comes in, and there are common types of validation. These examples illustrate how to handle them using React Hook Form.

  1. Required Validation

It is a validation that prompts the user to enter data in an input field in case it is empty. Developers commonly use it to ensure that users enter the input of mandatory fields. An excellent example is the username field when registering since the user will need it to log in it. The following code shows how to validate such a field.

<input

type=’text’

placeholder=’username’

{…register(“username”, { required: true })}

/>

If you use the above validation code, the application won’t allow the user to leave the username field empty when registering. The same should apply to the login interface. The following code ensures that users fill both fields, and failure to do so displays respective errors;

import “./App.css”;

import { useForm } from “react-hook-form”;

function App() {

const {

register,

handleSubmit,

formState: { errors },

} = useForm();

const onSubmit = (data) => {

alert(data);

};

return (

<div className=’App’>

<form onSubmit={handleSubmit(onSubmit)}>

{/* Username */}

<section>

<label>Enter username</label>

<input

type=’text’

placeholder=’username’

{…register(“username”, { required: true })}

/>

{errors.username && <span>Username is required</span>}

</section>

{/* Age */}

<section>

<label>Enter age</label>

<input

type=’number’

placeholder=’age’

{…register(“age”, { required: true })}

/>

{errors.age && <span>Age is required</span>}

</section>

{/* Submit button */}

<section>

<input type=’submit’ />

</section>

</form>

</div>

);

}

export default App;

  1. Min Length Validation

As the name suggests, this validation limits the minimum length of a value that a user can enter in a form field. For instance, if we set the above code to accept a username of at least 8 characters, this is how the code should look like. So, let’s add another validation to our username besides what is required to this effect.

{/* Username */}

<section>

<label>Enter username</label>

<input

type=’text’

placeholder=’username’

{…register(“username”, { required: true, minLength: 8 })}

/>

{errors.username?.type === “required” && (

<span>Username is required</span>

)}

{errors.username?.type === “minLength” && (

<span>Username must be at least 8 letters long</span>

)}

</section>

  1. Max Length Validation

On the other hand, developers want to ensure that users remember their inputs, especially in fields such as usernames. They will use them to log in and hence need something memorable. Limiting the length can help; this example shows how to go about it.

{/* Username */}

<section>

<label>Enter username</label>

<input

type=’text’

placeholder=’username’

{…register(“username”, {

required: true,

minLength: 8,

maxLength: 12,

})}

/>

{errors.username?.type === “required” && (

<span>Username is required</span>

)}

{errors.username?.type === “minLength” && (

<span>Username must be at least 8 letters long</span>

)}

{errors.username?.type === “maxLength” && (

<span>Username must not be 12 letters long</span>

)}

</section>

Since we had set the minimum length to 8, introducing the maximum limit of 8 means that the length of the user username can only be between 8 and 12 characters.

  1. Max Validation

Whereas maximum length limits the number of characters, this validation focuses on the entered values, usually numbers. For example, if an application targets the youth, the maximum age can be set to 35. It ensures that only the youth register, and the code should be as follows;

{/* Age */}

<section>

<label>Enter age</label>

<input

type=’number’

placeholder=’age’

{…register(“age”, { required: true, max: 35 })}

/>

{errors.age?.type === “required” && <span>Age is required</span>}

{errors.age?.type === “max” && <span>Age is too high</span>}

</section>

 

This code ensures that no one aged above 35 years can register.

 

  1. Min Validation

In the same vein, you don’t want underage people joining a program that’s not appropriate for their age. Therefore, a need to limit the minimum age may arise. If so, this is a perfect react-hook-form guide with examples for this validation.

{/* Age */}

<section>

<label>Enter age</label>

<input

type=’number’

placeholder=’age’

{…register(“age”, { required: true, min: 18, max:35 })}

/>

{errors.age?.type === “required” && <span>Age is required</span>}

{errors.age?.type === “min” && <span>Age is too small</span>}

</section>

 

Since we had already set the max to 30, the age of the application’s users range from 18 to 35 years.

Pattern Validation

This validation helps establish uniformity of what various users enter in a certain input field. For example, some users may choose capital letters, whereas others use small letters. It can make the records look untidy but React Hook Form will fix it using the following validation code;

{/* Username */}

<section>

<label>Enter username</label>

<input

type=’text’

placeholder=’username’

{…register(“username”, {

required: true,

minLength: 8,

maxLength: 12,

pattern: /[a-z]/,

})}

/>

{errors.username?.type === “required” && (

<span>Username is required</span>

)}

{errors.username?.type === “minLength” && (

<span>Username must be at least 8 letters long</span>

)}

{errors.username?.type === “maxLength” && (

<span>Username must not be 12 letters long</span>

)}

{errors.username?.type === “pattern” && (

<span>Username must be lowercase</span>

)}

</section>

Users will get an error message if they use capital letters when filling in the username field.

React Hook Form: Error Handling

We have looked at the various validations and how to implement them. However, implementing them isn’t enough if there are no consequences. It would be best if you defined what happens when the users don’t obey these rules, and that’s error handling. In React Hook Form, here is how to go about it;

You can use the formState property that’s in the useForm hook. In this case, access to the validation errors is through an error object from the property as follows;

const { formState: { errors } } = useForm();

You can also use the following code to achieve the same

const { formState } = useForm()

const { errors } = formState;

 

If you want to detect a validation error of a certain field, follow this

{errors.inputBox && <span>Error occurred in inputBox</span>}

Access a certain validation error type using the error type as follows;

{errors.inputBox?.type === “validation-type” && <span>Custom error message</span>}

How to Use React Hook Form with Third-Party Components

If you plan to use a third-party UI component, you don’t have to give up on using React Hook Form. Not even when this external component doesn’t support ref because the library has a solution to it. You will still integrate the two seamlessly using its Controller component.

In this case, you will useForm Hook’s object, control, which works similarly with the register method to register that external UI component.

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *