DEV Community

Cover image for "Well you just got to, got to, got to, got to get in touch"
Max Zander
Max Zander

Posted on • Updated on

"Well you just got to, got to, got to, got to get in touch"

Over this last week I've been working on building a webpage for a small business. I decided to build it with React since I love the way that React lets me build and to build it with only a front-end, since a backend didn't feel totally necessary for this project. The biggest challenge I realized that I would come across by not using a backend was going to be the contact form. The business's owner wanted a pretty simple form that potential clients could fill out to get in touch and until this last week, I was unsure of how to accomplish such a thing without also creating a backend database. Luckily, there was a very simple solution and I'll share that with you now!

So, to build the contact form, I used an awesome service called EmailJS. To get started, create an account with EmailJS and click on the button that says "Add New Service". Then, you can set up EmailJS to connect with the your email account. Now, I should say that EmailJS has several levels of membership and a whole bunch of email providers that can be used in conjunction with the service, but for this project, I'm starting us out with the free version to test things out and and I connected the business owner's Gmail account. Connecting an email account gives you a Service ID, which you'll need a little later.

You're also going to want to think out how you want the contact form to be laid out. Once you have an idea, click on the button on the sidebar that says "Email Templates" and then the button that says "Create New Template". Once you're there, you can input whatever you want sent to you. Anything that you need to interpolate later, goes within two curly braces {{}}.

For example, the template that I created for this project looks like this:

{{name}}

{{email}}

Message:
{{message}}
Enter fullscreen mode Exit fullscreen mode

and has a subject:

Website Message from {{name}}
Enter fullscreen mode Exit fullscreen mode

You can change the title of your template under "Settings" and, for the record, the only other required thing to fill out is the "To Email" and "From Email" (although, changes to the latter are not permitted for personal services). *For this project, I did add the submitted email ({{email}}) as the "Reply To" so that the business owner can just reply to the email if she wishes to get directly in touch with whomever filled out the form.

Okay! So now we get to the fun part -- let's add the form into our code! First things first, add EmailJS to your package by running:

npm install emailjs-com --save
Enter fullscreen mode Exit fullscreen mode

Then create your Contact.js component and, once you've imported React from 'react', make sure to add import emailjs from 'emailjs-com';. The basic shape of the component will look something like this:

import React from 'react';
import emailjs from 'emailjs-com';

const Contact = () => {
}

export default Contact;
Enter fullscreen mode Exit fullscreen mode

EmailJS offers some great docs, including docs for React which you can find here. From those docs, I grabbed the following code:

  function sendEmail(e) {
    e.preventDefault();

    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target, 'YOUR_USER_ID')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  }
Enter fullscreen mode Exit fullscreen mode

Pop that code in before your return statement and swap out where it says 'YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', and 'YOUR_USER_ID' for the values that you'll find in your EmailJS account. The SERVICE_ID will be listed under your Email Service, your TEMPLATE_ID, will be listed under the template you created, and your USER_ID can be found under the "Integration" tab of the sidebar.

Then, in your return, create your form. I added require to my inputs to make sure that people can't submit the form without inputting all of the data that the business will need. In the code, my form looks as follows:

 <form onSubmit={sendEmail}>
                    <input type="text" placeholder="Name (Required)" name="name" required />
                    <br />
                    <input type="text" placeholder="Email (Required)" name="email" required />
                    <br />
                    <textarea type="text" placeholder="Your Message (Required)" name="message" required />
                    <br />
                    <input type="submit" value="Send Message" />
                </form>
Enter fullscreen mode Exit fullscreen mode

You'll notice that onSubmit, we call the sendEmail function that we added from the docs.

*** I did make one change to the sendEmail function, so that the person submitting the form gets an alert telling them whether the form was submitted successfully. If you would like to add that functionally, you can change the function to look as follows:

    function sendEmail(e) {
      e.preventDefault();

        emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', e.target, 'YOUR_USER_ID')
        .then((result) => {
            console.log(result.text);  alert("Message sent successfully!");
        }, (error) => {
            console.log(error.text); alert("Failed."+error);
        });
        e.target.reset()
    }
Enter fullscreen mode Exit fullscreen mode

Finally, add whatever CSS you wish to style, but guess what -- you should be functional now (no pun intended)!

Ultimately, the form I created for the site currently looks like this:
Alt Text
It is fully functional, and hopefully will help this business owner bring their products to an even wider audience!

Top comments (2)

Collapse
 
xr0master profile image
Sergey Khomushin

Hey Max. Thank you very much for your excellent article!
I would like to point out a few small amendments:

  1. We strongly recommend using double curly braces for the dynamic variables, as this method is safer. It escapes variable values, which reduces the chance of abuse.
  2. The "From Email" field cannot be changed for Personal services, because the email servers will assume you are impersonating another person. This limitation applies to any accounts' tier.

Have a nice day!

Collapse
 
maxjacobzander profile image
Max Zander

Thanks so much for your compliment and for the amendments, Sergey! I've updated the article to reflect the changes!

Have an awesome rest of your week!