Using React-Hook-Form

Today we are using the NextJS framework to create a contact form for a website. NextJS is a popular framework for building server-rendered React applications, which allows for efficient and optimized rendering of pages on the server. The code also makes use of two additional modules: "react-hook-form" and "axios". The "react-hook-form" module provides a simple and easy-to-use API for handling forms in React applications. It allows for easy validation of form fields and provides methods for registering and managing form fields and the "axios" module allows us to make https requests to API endpoints. Overall, this code provides a basic example of how to create a contact form using NextJS and these two additional modules.
Technologies used:
  • NextJS
  • React-Hook-Form
  • Axios
  • Tailwind

The first two lines import the necessary modules for the form to function properly.

import { SubmitHandler, useForm } from "react-hook-form";
import axios from "axios";
import { BaseSyntheticEvent, useState } from "react";

Next, we define the FormData and FieldData types. The FormData type is used to define the shape of the data that the form will be expecting, and the FieldData type is a generic type that will be used to specify the type of the data that the useForm hook returns.

type FormData = {
	name: string;
	email: string;
	message: string;
	phone: string;
};
type FieldData = any;

Then, we define the Contact component, which is a functional component that will render the contact form. Inside the component, we use the useState hook to create a state variable called formState and a setter function called setFormState. This state variable will be used to keep track of the form's submission status.

const Contact = () => {
	const [formState, setFormState] = useState(false);
	...
};

Next, we define the onSubmition function, which will be passed as a prop to the form element's onSubmit event handler. This function will be called when the form is submitted, and it will make an https POST request to the server-side API using axios. If the request is successful, the form is reset and an alert is displayed to the user. If there is an error, it is logged to the console.

const onSubmition: SubmitHandler<FieldData> = async (
	values: FormData,
	event: BaseSyntheticEvent<object, any, any> | undefined
) => {
	let config = {
		method: "post",
		url: "/api/contact", //API endpoint of the action
		headers: {
			"Content-Type": "application/json",
		},
		data: values,
	};

	try {
		setFormState(true);
		const response = await axios(config);
		if (response.status == 200) {
			event?.target.reset();
			setFormState(false);
			alert("Message sent!");
		}
	} catch (err) {
		console.error(err);
	}
};

Finally, we use the useForm hook to create the form element. This hook returns an object containing several methods and properties that we can use to control the form, such as register, handleSubmit, watch, and formState.

The register method is used to register the form fields, and the handleSubmit method is used to handle the form's submission. The watch method is used to watch the values of the form fields

In this case, we are specifying that the name field is required and has a minimum length of 4 characters.

const {
	register,
	...
} = useForm();

...

<input
	{...register("name", {
		required: "Name is required",
		minLength: {
			value: 4,
			message: "Name must be at least 4 characters long",
		},
	})}
	className="form-input rounded-md shadow-sm block w-full py-2 px-3 leading-5 focus:outline-none focus:shadow-outline-blue-500"
	placeholder="Name"
	type="text"
/>

The handleSubmit method is used to handle the form's submission. It takes a callback function as an argument, which in this case is the onSubmition function that we defined earlier. This function will be called when the form is submitted, and it will make an https POST request to the server-side API using axios.

const {
	...
	handleSubmit,
	...
} = useForm();

...

<form
	onSubmit={handleSubmit(onSubmition)}
	className="text-myblack space-y-4"
>

The watch method is used to watch the values of the form fields, and it takes a field name as an argument. It returns the current value of the field, which can be used to display the value in the form or to perform some other action.

const {
	...
	watch,
	...
} = useForm();

...

<input
	{...register("email")}
	className="form-input rounded-md shadow-sm block w-full py-2 px-3 leading-5 focus:outline-none focus:shadow-outline-blue-500"
	placeholder="Email"
	type="email"
	value={watch("email")}
	onChange={(e) => setEmail(e.target.value)}
/>

Finally, the formState property contains the state of the form, including any errors that may have occurred during validation. We can use this property to display error messages to the user or to disable the form while it is being submitted.

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

...

{errors.name && <div className="text-red-600">{errors.name.message}</div>}

That's it! This is a basic example of how to create a contact form in a React application using the react-hook-form library and axios to make an https POST request to a server-side API. I hope this helps! Let me know if you have any questions.

Feel free to contact me for any question :)
I'll be getting back to you as soon as possible

+51 935 818 561
Lima, Perú

🟥⬜🟥