DEV Community

Cover image for Contact form with react-hook-form and emailjs
Marcos Nikel
Marcos Nikel

Posted on • Edited on

Contact form with react-hook-form and emailjs

What I Wanted to Do

Today, I started developing my portfolio, and one thing I really wanted to do was create a contact form through which people could reach out to me via email. Since I had never done this before, I found myself wondering, "How can I do this?"

The Solution

Then, I remembered a library that I had been eager to learn, react-hook-form. I thought it was the perfect opportunity to learn it because it provides amazing control over form data. However, I had no idea how to send the data to my email. After conducting a brief search, I came across various possibilities, but one that caught my eye was the emailjs library. It was user-friendly and only required a public key, an email template ID, and a service ID from emailjs. Additionally, I had to make some minor configurations in VSCode. In this article, I will provide an example of how to configure emailjs.

Image description

-> In the image above, you can see that I call the register method from the hook form, which is responsible for keeping track of the form data. In the next image, you will see that I call the same method in my inputs to assign a name to the input.

-> The handleSubmit method, also from hook form, handles the form submission. We pass our other function, onSubmit, to this method so that it can be executed. The reset function is used to reset the input's state, setting the values back to empty strings (" ").

In the onSubmit function, you need to set the template to send to the emailjs email template mentioned earlier. The keys from, name, fromEmail, and message are important, as you will see shortly.

We call emailjs, passing the SERVICE_ID and TEMPLATE_ID that you select in your emailjs dashboard. I create two variables to store the values for me, and the third parameter represents your template parameters, which I define in the onSubmit function.

In the image below, you can see the register method for the inputs mentioned earlier, as well as the form validations. That's pretty much all you need to do in your code.

Image description

The last important thing is to ensure that the variables' names in your onSubmit function match the keys in the object within the email template on the emailjs dashboard, as shown below:

Image description

As you can see, I used the same names for my keys in the object. This is how emailjs recognizes the data when it is sent to the emailjs API.

That's it for today, guys! You can learn more about react-hook-form and emailjs in their respective documentation. I will provide the links below:

Top comments (0)