Creative Designs Guru

How to Create and Handle NextJS form with React Hook Form

December 27, 2020

Creating a form from scratch without any libraries was easy in React framework. But, handling the logic was extremely difficult when you start validating directly in the frontend or send requests to the server.

You can create and handle forms in an elegant way with React Hooks. For your information, React Hooks was introduced in React 16.8. By using Hooks, it gives developers a new pattern to make code more reusable.

Instead of reinventing the wheel by writing your own hooks, you should use React Hook Form. As the name indicates, it uses React Hooks to build form and 100% compatible with NextJS.

Install React Hook Form dependency

Before starting anything, you need to install React Hook Form as a dependency with the following command:

npm install react-hook-form

In your pages folder from Next JS framework, you can import this new library in your React code:

import { useForm } from 'react-hook-form';

Create a newsletter sign up form

After importing React Hook Form, we need to create the visual part of the form. In our example, we'll build an easy newsletter subscription form. Here is the starting point:

export default function Index() {
return (
<form>
<input name="email" />

<input type="submit" />
</form>
);
}

Nothing fancy, it's just a classic form in React with one input for email and another input for submitting the form.

Join my Newsletter for JS Devs
Get helpful content about Full-Stack React development with Next JS and Tailwind CSS. No spam, unsubscribe at any time.

Form error management

Then, we need to connect the input to React Hook Form by using register method provided by the library.

import { useForm } from "react-hook-form";

export default function Index() {
const { register } = useForm();
...
<input name="email" ref={register({ required: true })} />
...

In register method, we also add required: true. As its name suggested, the user can't leave the input empty when he submits the form.

After registering the input, we need to display an error message when the user doesn't fill the form. The good news React Hook Form also provides errors object to handle form errors.

export default function Index() {
const { register, errors } = useForm();
...
<input name="email" ref={register({ required: true })} />
{errors.email && <span>The email is required</span>}
...

Handle the form logic

As you may notice, nothing happens when you start submitting the form. So, we need to implement the validation process. When everything is correct, we also need to retrieve the user email and send it to your backend (or do what you need to do based on your need).

handleSubmit method needs to be used for validating forms in React Hook Form. handleSubmit takes as his first argument the callback when the form is correctly filled by the user. Here is an example of how to use handleSubmit method:

export default function Home() {
const { handleSubmit, register, errors } = useForm();
const onSubmit = (data: any) => console.log(`Email input value: ${data.email}`);

return (
<form onSubmit={handleSubmit(onSubmit)}>
...

You have to replace console.log method based on your requirement. For example, you can call a backend server with data from the form filled by the user.

In conclusion

Finally, you can find the complete source code here:

import { useForm } from 'react-hook-form';

export default function Home() {
const { handleSubmit, register, errors } = useForm();
const onSubmit = (data: any) => console.dir(`Email input value: ${data.email}`);

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="email" ref={register({ required: true })} />

{errors.email && <span>This email is required</span>}

<input type="submit" />
</form>
);
}

As you can see, with React Hook From library, it makes form handling so easy. You can now make a form in NextJS and in React with only a few lines of code.

In my previous article, I've also written an tutorial on how to set up Next JS with ESLint Prettier to write high quality code with less errors. You can add TypeScript on top of that for writing React application with type checking.

You can also check out my portfolio at Next JS Tailwind themes built in modular way with React components and TypeScript.

NextJS templates themes