Thu Oct 24 2024
How to Use React Hook Form to Submit a Form in Next.js
Form handling in React can be tricky, but React Hook Form makes it easier and more efficient by reducing the amount of boilerplate code required. React Hook Form integrates and works smoothly with Next.js. It provides you a powerful tool to manage forms with validation, submission, and error handling. In this article, I'll cover how to use React Hook Form to create and submit a form in a Next.js application.
Step 1: Create a Form Component with React Hook Form
First, create a new component where you’ll build the form. I create a simple form with fields for first name, last name, email, contact number and message, and handle form validation using React Hook Form. React Hook Form only works on the client side. So, in case Nextjs 14+ you must add use client at the top of the component page.
<form className="mt-5" onSubmit={handleSubmit(dataSubmit)}>
<div className="flex flex-col md:flex-row gap-3 md:gap-6 my-3">
<div className="w-full md:w-1/2">
<input
type="text"
placeholder="First Name"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("firstName", { required: true })}
/>
</div>
<div className="w-full md:w-1/2">
<input
type="text"
placeholder="Last Name"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("lastName", { required: true })}
/>
</div>
</div>
<div className="flex flex-col md:flex-row gap-3 md:gap-6 my-3">
<div className="w-full md:w-1/2">
<input
type="email"
placeholder="E-mail"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("email", { required: true })}
/>
</div>
<div className="w-full md:w-1/2">
<input
type="tel"
placeholder="Contact No."
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("contactNo")}
/>
</div>
</div>
<div className="my-3">
<textarea
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none min-h-32"
{...register("message")}
placeholder="Message"
></textarea>
</div>
<div className="flex items-center justify-end mt-6">
<p className="text-white font-medium text-lg mr-4">{msg}</p>
<button
type="submit"
className="bg-white rounded text-black hover:bg-green transition-all ease-linear py-2 px-3 font-medium uppercase shadow-md"
>
Send Message
</button>
</div>
</form>
Step 2: Form Validation and Error Handling
React Hook Form makes it easy to validate forms using the register function. In the form fields above, we added rules for validation like required as true for required fields. You can also add pattern matching for the email, and a minimum length for the password field. The error messages will automatically show up when the user submits invalid data. You can customize the validation rules and error messages to fit your requirements.
{errors.firstName && <p>{errors.firstName.message}</p>}
Step 3: Handling Form Submission
The handleSubmit method in React Hook Form takes care of handling the form submission. In the onSubmit function, you can log or send the form data to a server.
<form className="mt-5" onSubmit={handleSubmit(dataSubmit)}>
...
</form>
const dataSubmit = (data: any) => {
if (data) {
setMsg("Thank You For Contacting US!");
reset();
}
};
Conclusion
Using React Hook Form in a Next.js project provides a simple yet powerful way to handle forms with minimal code. With built-in validation, error handling, and the ability to integrate easily with APIs, it becomes a highly efficient solution for form management. By following the steps outlined in this article, you should now have a basic understanding of how to create a form using React Hook Form and submit the form data in a Next.js application. You can extend this example by adding more fields, custom validation logic, and more sophisticated form submission processes depending on your project’s needs. You can download the travel guide website template from WebGraphiz.com.File Name: contactForm.tsx
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
const ContactForm = () => {
const { register, reset, handleSubmit } = useForm();
const [msg, setMsg] = useState<string>();
const dataSubmit = (data: any) => {
if (data) {
setMsg("Thank You For Contacting US!");
reset();
}
};
return (
<form className="mt-5" onSubmit={handleSubmit(dataSubmit)}>
<div className="flex flex-col md:flex-row gap-3 md:gap-6 my-3">
<div className="w-full md:w-1/2">
<input
type="text"
placeholder="First Name"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("firstName", { required: true })}
/>
</div>
<div className="w-full md:w-1/2">
<input
type="text"
placeholder="Last Name"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("lastName", { required: true })}
/>
</div>
</div>
<div className="flex flex-col md:flex-row gap-3 md:gap-6 my-3">
<div className="w-full md:w-1/2">
<input
type="email"
placeholder="E-mail"
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("email", { required: true })}
/>
</div>
<div className="w-full md:w-1/2">
<input
type="tel"
placeholder="Contact No."
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none"
{...register("contactNo")}
/>
</div>
</div>
<div className="my-3">
<textarea
className="w-full text-lg px-4 py-1.5 rounded shadow-md outline-none min-h-32"
{...register("message")}
placeholder="Message"
></textarea>
</div>
<div className="flex items-center justify-end mt-6">
<p className="text-white font-medium text-lg mr-4">{msg}</p>
<button
type="submit"
className="bg-white rounded text-black hover:bg-green transition-all ease-linear py-2 px-3 font-medium uppercase shadow-md"
>
Send Message
</button>
</div>
</form>
);
};
export default ContactForm;