DEV Community

Cover image for How I Integrated Emailjs Form Handling in my React App
Blessing Peters
Blessing Peters

Posted on • Updated on

How I Integrated Emailjs Form Handling in my React App

As a front-end developer, at some point you may need to capture information from people who use your website through your contact forms. Platforms like emailJs, Netlify forms, forms-pree, etc. make this possible by allowing sending an email directly from your Javascript with no backend development

Email JS is a powerful tool for email form handling in React apps. It allows developers to quickly and easily add email forms to their React applications without having to write any code or manually manage any backend services. The platform offers an easy-to-use user interface that allows you to quickly generate email templates with dynamic attributes. In this article, I'll show you how I was able to integrate Email JS into my React app.

Prerequisites

To follow along with this article, you should:

  • Already have basic knowledge of the React library and how to create a React app. if you're new to React please visit reactjs.org or create-react-app.dev/ to get started.

Firstly, I created a new React app by running the following command in my terminal:

npx create-react-app my-form-app 
Enter fullscreen mode Exit fullscreen mode

cd into the app folder and run the following command to start the development server

cd my-form-app
npm start
Enter fullscreen mode Exit fullscreen mode

I opened the app.js in the src folder and went ahead to remove all the unnecessary code from it; it should look like this

Image description

Getting started.

Step 1: Create an account
I created an account on Emailjs.com website; The website interface typically looks like this:

Image description

once done, confirmed my email, and logged in.
After login, I was taken to the admin dashboard, which will look like this:

Image description

Step 2: Configure Your Email JS Setting
Next, I click on the “Add New Service” Icon in order to to create and add an email service that will be used to send emails. When you click on it, a screen asking you to select your preferred email service will appear.

Image description

From here, I clicked on Connect Account; where redirected me to my email provider to confirm the connection. once finalized, I finish this step by clicking on Create Service and the email service is all set.

The new email service on the home page is as shown below:
Image description

Create and customize an email template
after creating an email service the next thing was to create an email template.
Image description

To do this, click on “Email Templates” and then “Create New Template”. This is what it will look like:
Image description

Then I customised it to be like this:
Image description

The curly brackets are dynamic parameters, To reflect what is sent to EmailJs.

  • from_name: this has to do with the name of the person sending the email through the contact form.

  • to_name: this has to do with the receiver's name. That's me since I'm the owner of the Gmail account to which the email is being sent to.

  • message: this has to do with the sender’s message.

  • reply_to: this has to do with the sender’s email.

  • phone_number: while this is the sender’s number.
    All these parameters will be used during the implementation in the react app

Side Note:
you can move on to the next tab ' Auto-Reply ' and enable autoreply back to the sender; Make sure to tick the box mentioning Auto-Reply if you want a reply sent to your user.

Image description

Step 3: Implementation
Now I'm ready to implement emailjs form handling functionality in my react app. Please check the official emailjs documentation for detailed explanations.

Install the Email JS React Library
This provides an easy way to integrate Email JS into your React application. It can be installed using the following command:

npm install @emailjs/browser
Enter fullscreen mode Exit fullscreen mode

Next is to import the following at the top of your app.js

import React, { useState } from 'react';
import emailjs from "@emailjs/browser";
Enter fullscreen mode Exit fullscreen mode

After importing I created a basic react form which should look like this:

<div className="container">
        <h1>Contact page</h1>
        <form className="form" onSubmit={onSubmit}>
          <div className="form-group">
            <input
              className="form-control"
              type="text"
              name="from_name"
              value={from_name}
              onChange={onChange}
              id="from_name"
              placeholder="Enter Fullname"
            />
          </div>
          <div className="form-group">
            <input
              className="form-control"
              type="text"
              name="reply_to"
              value={reply_to}
              onChange={onChange}
              id="reply_to"
              placeholder="Enter Email"
            />

          </div>
          <div className="form-group">
            <input
              className="form-control"
              type="tel"
              name="phone_number"
              value={phone_number}
              onChange={onChange}
              id="phone_number"
              placeholder="Enter Phone Number"
            />

          </div>
          </div>
          <div className="form-group">
            <textarea
              className="form-control"
              name="message"
              value={message}
              onChange={onChange}
              id="message"
              placeholder="Enter Message"
            ></textarea>
          </div>
          <button type="submit" id="button">
            Submit
          </button>
        </form>
      </div>
Enter fullscreen mode Exit fullscreen mode

There are a few things worth mentioning in the form above:

  • The required attribute is for basic validation. which prevents incomplete forms to be submitted by the user.
  • The name and value attributes in the input fields are the same as the dynamic parameters created in the email templates.
  • In the opening tag of the form, the onSubmit attribute would trigger the onSubmit function.

  • I created a state formData that is an object which tracks all the changes happening in the form.

 const [formData, setFormData] = useState({
    from_name: "",
    reply_to: "",
    phone_number: "",
    company_name: "",
    message: ""
  });
  const { from_name, reply_to, phone_number, company_name, message } = formData;
Enter fullscreen mode Exit fullscreen mode
  • In theonChange attribute I set the formData by first using a spread operator ... to list the items in the state object and then match the input ID with the input value by using e.target so as to capture and update the changes in the input fields.
  const onChange = (e) => {
    setFormData({
      ...formData,
      [e.target.id]: e.target.value
    });
  };
Enter fullscreen mode Exit fullscreen mode
  • Check out the onSubmit function below.
const onSubmit = (e) => {
    e.preventDefault();

    formData["to_name"] = "Blessing Peter";

    const YOUR_SERVICE_ID = "service_k5uanup";
    const YOUR_TEMPLATE_ID = "template_1i82n0k";
    const YOUR_PUBLIC_KEY = "ZTxRbsirc1MJiUsQ9";

    emailjs.send(YOUR_SERVICE_ID, YOUR_TEMPLATE_ID, formData, YOUR_PUBLIC_KEY).then(
      () => {
        console.log("Email Sent")
        setFormData({
          from_name: "",
          reply_to: "",
          phone_number: "",
          company_name: "",
          message: ""
        });
      },
      (error) => {
        console.log(JSON.stringify(error));
      });
    console.log(formData);
  };

Enter fullscreen mode Exit fullscreen mode

This is the breakdown to understand it better:

  • e is passed as a parameter.

  • e.preventDefault() would prevent the page from being reloaded when submitted.

  • Since the formData state is an object, and objects are key collection items I created a new key["to_name"] and gave it a value "Blessing Peter". Note that ["to_name"] is also a dynamic parameters created in the email templates.

  • emailjs.sendForm() takes four parameters,a service ID (that was created earlier), a template ID (also created earlier and can be seen in the email template settings), and a Public Key (that is seen in the account settings ) all of which values I saved in a const variable.

  • Since emailjs.sendForm() is a promise (asynchronous) I follow it with .then.

  • In the .then I console.log email Sent and also reset the formData state to an empty string "" so that the form is cleared if successful or the error if unsuccessful (since the error is coming from the server JSON.stringify turns it to a string).

That’s it, we can now receive emails straight from our app without creating a backend!

you can check out the replit link here

Thanks for reading! I hope you learned a thing or two ❤️

Top comments (2)

Collapse
 
xr0master profile image
Sergey Khomushin

Thanks for your wonderful article!

Collapse
 
blessingpeters profile image
Blessing Peters

You're welcom