React Contact Form

Without Backend, Sent via Email (or Slack)

Forms Example

This guide will show you how to make a nice-looking and elegant form with React. Contact form creation in React shouldn't be a tedious task if you're working on a static/jamstack site.

Often, different guides suggest using backend NodeJS/PHP servers for storing/emailing data. But it's not an absolute rule if you think smart, and your codebase can be a lot cleaner with the fronted-only code.

Create the React app

(if you're starting a brand new project)

In case you're starting a brand new project, you'll need some initial steps. One of the most straightforward ways is to use the create-react-app package. To start:

  • Open the terminal and install the create-react-app package
    npm install create-react-app --global
  • Go to the directory where you will store your project. For example
    mkdir ~/react-project && cd ~/react-project
  • Then create your app in this folder; this will be your project root folder
    npx create-react-app .
  • When the installation has finished, you can start the server
    npm start

Use your favorite code editor to work with files in ~/react-project/src. You will be able to make a contact form there.

Create the contact form component

Create a new file called ContactForm.js in the src folder. You can use any fields and any framework for styling your code. For now, we're staying with the standard "Name," "Email," and "Message" for the simple contact form. We're also going to use TailwindCSS to make it beautiful, but you can use your own custom CSS code too.

1import React, { useState } from "react";
2
3const FORM_ENDPOINT = ""; // TODO - fill on the later step
4
5const ContactForm = () => {
6  const [submitted, setSubmitted] = useState(false);
7  const handleSubmit = () => {
8    setSubmitted(true);
9  };
10
11  if (submitted) {
12    return (
13      <>
14        <div className="text-2xl">Thank you!</div>
15        <div className="text-md">We'll be in touch soon.</div>
16      </>
17    );
18  }
19
20  return (
21    <form
22      action={FORM_ENDPOINT}
23      onSubmit={handleSubmit}
24      method="POST"
25      target="_blank"
26    >
27      <div className="mb-3 pt-0">
28        <input
29          type="text"
30          placeholder="Your name"
31          name="name"
32          className="px-3 py-3 placeholder-gray-400 text-gray-600 relative bg-white bg-white rounded text-sm border-0 shadow outline-none focus:outline-none focus:ring w-full"
33          required
34        />
35      </div>
36      <div className="mb-3 pt-0">
37        <input
38          type="email"
39          placeholder="Email"
40          name="email"
41          className="px-3 py-3 placeholder-gray-400 text-gray-600 relative bg-white bg-white rounded text-sm border-0 shadow outline-none focus:outline-none focus:ring w-full"
42          required
43        />
44      </div>
45      <div className="mb-3 pt-0">
46        <textarea
47          placeholder="Your message"
48          name="message"
49          className="px-3 py-3 placeholder-gray-400 text-gray-600 relative bg-white bg-white rounded text-sm border-0 shadow outline-none focus:outline-none focus:ring w-full"
50          required
51        />
52      </div>
53      <div className="mb-3 pt-0">
54        <button
55          className="bg-blue-500 text-white active:bg-blue-600 font-bold uppercase text-sm px-6 py-3 rounded shadow hover:shadow-lg outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
56          type="submit"
57        >
58          Send a message
59        </button>
60      </div>
61    </form>
62  );
63};
64
65export default ContactForm;

Embed component into your app, enable styling

Open App.js in your src folder, add contact form component, and enable TailwindCSS. If it's an existing project, open the file where the contact form should appear. You need to:

  1. Import ContactForm — line number #4
  2. Add TailwindCSS (the example is for demo purposes only, for the production please refer to the TailwindCSS installation) — line number #9
  3. Display ContactForm — line number #24
1import logo from "./logo.svg";
2import "./App.css";
3import { useEffect } from "react";
4import ContactForm from "./ContactForm";
5
6function App() {
7  // You can skip useEffect if you're not using TailwindCSS
8  // Otherwise, for the production usage refer to https://tailwindcss.com/docs/installation
9  useEffect(() => {
10    if (document) {
11      const stylesheet = document.createElement("link");
12      stylesheet.rel = "stylesheet";
13      stylesheet.href = "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css";
14
15      document.head.appendChild(stylesheet);
16    }
17  }, []);
18
19  return (
20    <div className="App">
21      <header className="App-header">
22        <img src={logo} className="App-logo" alt="logo" />
23        <div className="py-6">
24          <ContactForm />
25        </div>
26      </header>
27    </div>
28  );
29}
30
31export default App;

Create the free HeroTofu forms backend

Head over to herotofu.com and create an account. It will handle all the boring and complex form submission process work for you. You'll get 14 days of the free trial at first, and later you can leave it with the free forever plan. For the sole purpose of the contact form, it's usually more than enough.

HeroTofu registration is straightforward. Fill in the basic fields and then confirm your email address.

Herotofu signup

Once you have confirmed your email address, go to app.herotofu.com/forms to create your first form. Fill in the form name and add your preferred email address where you'd like to receive your form submits. Slack and Zapier are also options, but you need to pay for them once the trial is over.

You'll get the form endpoint URL once you hit submit, so remember to copy it.

Herotofu Forms List

Use the created forms backend in your contact form

Once again, open the ContactForm.js file and fill in the form endpoint URL. You need to change the FORM_ENDPOINT variable at the top of the file. It should look like this.

1import React, { useState } from "react";
2
3const FORM_ENDPOINT = "https://public.herotofu.com/v1/6fe31160-d190-11ef-856e-8323ab6b61ae";
4
5// The rest of the code...

Done! Go ahead and test your contact form submission! You don't need to do any backend email work, as HeroTofu will handle everything.

Bonus: advanced React implementation

As you can see, the implementation is basic, and you only get those fields on the contact form that are visible on the HTML. That might not work if you need a more customized flow. You'll need to adjust the handleSubmit handler function to inject extra data dynamically. Good examples could be the user id, the selected plan, or some meta-information of site usage. It should make an ajax call to the FORM_ENDPOINT instead of the regular form submits. Here's how it could look like in practice.

1import React, { useState } from "react";
2
3const FORM_ENDPOINT = ""; // TODO - fill on the later step
4
5const ContactForm = () => {
6  const [status, setStatus] = useState();
7  const handleSubmit = (e) => {
8    e.preventDefault();
9
10    // Anything you need to inject dynamically
11    const injectedData = {
12      DYNAMIC_DATA_EXAMPLE: 123,
13    };
14    const inputs = e.target.elements;
15    const data = {};
16
17    for (let i = 0; i < inputs.length; i++) {
18      if (inputs[i].name) {
19        data[inputs[i].name] = inputs[i].value;
20      }
21    }
22
23    Object.assign(data, injectedData);
24
25    fetch(FORM_ENDPOINT, {
26      method: "POST",
27      headers: {
28        Accept: "application/json",
29        "Content-Type": "application/json",
30      },
31      body: JSON.stringify(data),
32    })
33      .then((response) => {
34        // It's likely a spam/bot request, so bypass it to validate via captcha
35        if (response.status === 422) {
36          Object.keys(injectedData).forEach((key) => {
37            const el = document.createElement("input");
38            el.type = "hidden";
39            el.name = key;
40            el.value = injectedData[key];
41
42            e.target.appendChild(el);
43          });
44
45          e.target.submit();
46          throw new Error("Please finish the captcha challenge");
47        }
48
49        if (response.status !== 200) {
50          throw new Error(response.statusText);
51        }
52
53        return response.json();
54      })
55      .then(() => setStatus("We'll be in touch soon."))
56      .catch((err) => setStatus(err.toString()));
57  };
58
59  if (status) {
60    return (
61      <>
62        <div className="text-2xl">Thank you!</div>
63        <div className="text-md">{status}</div>
64      </>
65    );
66  }
67
68  return (
69    <form
70      action={FORM_ENDPOINT}
71      onSubmit={handleSubmit}
72      method="POST"
73      target="_blank"
74    >
75
76  // The rest of the code is the same...

The core idea is that you send a POST request to the FORM_ENDPOINT of your contact form. But it doesn't matter which way you do it. It can be a regular form submit with ajax handler upon form submission or a completely different request that doesn't involve HTML forms at all

Treat it as a REST API because as long as you're sending POST, you'll be good to go. Your react form submission will reach your inbox.

 
Contact Form Backend -- Start NowFree and Paid plans