React Post Form Data to API

Use React Hooks, Copy-Paste Code Available

Forms Example

This guide will teach you how to send form data to any API endpoint.

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 form data hook

Create a new file called UseForm.js in the src folder. The hook will intercept regular form submit and will send JSON data to the API endpoint.

import { useState } from "react";

function useForm({ form, additionalData, endpointUrl }) {
  const [status, setStatus] = useState("");
  const [message, setMessage] = useState("");

  const handleSubmit = (e) => {
    if (form) {
      e.preventDefault();
      setStatus("loading");
      setMessage("");

      const finalFormEndpoint = endpointUrl || form.action;
      const data = Array.from(form.elements)
        .filter((input) => input.name)
        .reduce(
          (obj, input) => Object.assign(obj, { [input.name]: input.value }),
          {}
        );

      if (additionalData) {
        Object.assign(data, additionalData);
      }

      fetch(finalFormEndpoint, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => {
          if (response.status !== 200) {
            throw new Error(response.statusText);
          }

          return response.json();
        })
        .then(() => {
          setMessage("We'll be in touch soon.");
          setStatus("success");
        })
        .catch((err) => {
          setMessage(err.toString());
          setStatus("error");
        });
    }
  };

  return { handleSubmit, status, message };
}

export default useForm;

Create the form component

Create a new file called Form.js in the src folder. You can use any fields and any framework for styling it. 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.

import { useRef } from "react";
import useForm from "./UseForm";

const FORM_ENDPOINT = "https://herotofu.com/start"; // TODO - fill on the later step

const Form = () => {
  const formElement = useRef(null);
  const additionalData = {
    sent: new Date().toISOString(),
  };

  const { handleSubmit, status, message } = useForm({
    form: formElement.current,
    additionalData,
  });

  if (status === "success") {
    return (
      <>
        <div className="text-2xl">Thank you!</div>
        <div className="text-md">{message}</div>
      </>
    );
  }

  if (status === "error") {
    return (
      <>
        <div className="text-2xl">Something bad happened!</div>
        <div className="text-md">{message}</div>
      </>
    );
  }

  return (
    <form
      action={FORM_ENDPOINT}
      onSubmit={handleSubmit}
      method="POST"
      target="_blank"
      ref={formElement}
    >
      <div className="mb-3 pt-0">
        <input
          type="text"
          placeholder="Your name"
          name="name"
          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"
          required
        />
      </div>
      <div className="mb-3 pt-0">
        <input
          type="email"
          placeholder="Email"
          name="email"
          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"
          required
        />
      </div>
      <div className="mb-3 pt-0">
        <textarea
          placeholder="Your message"
          name="message"
          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"
          required
        />
      </div>
      {status !== "loading" && (
        <div className="mb-3 pt-0">
          <button
            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"
            type="submit"
          >
            Send a message
          </button>
        </div>
      )}
    </form>
  );
};

export default Form;

Embed contact form 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 Form — 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 Form — line number #24
import logo from "./logo.svg";
import "./App.css";
import { useEffect } from "react";
import Form from "./Form";

function App() {
  // You can skip useEffect if you're not using TailwindCSS
  // Otherwise, for the production usage refer to https://tailwindcss.com/docs/installation
  useEffect(() => {
    if (document) {
      const stylesheet = document.createElement("link");
      stylesheet.rel = "stylesheet";
      stylesheet.href = "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css";

      document.head.appendChild(stylesheet);
    }
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <div className="py-6">
          <Form />
        </div>
      </header>
    </div>
  );
}

export default App;

Bonus: handle spam bots

If you're using HeroTofu forms backend it's easy to handle spam bots too. You have to check whenever the API returned 422 status code and redirect visitor to the captcha error page. This is done by modifying your hook around the line #34:

import { useState } from "react";

function useForm({ form, additionalData, endpointUrl }) {
  const [status, setStatus] = useState("");
  const [message, setMessage] = useState("");

  const handleSubmit = (e) => {
    if (form) {
      e.preventDefault();
      setStatus("loading");
      setMessage("");

      const finalFormEndpoint = endpointUrl || form.action;
      const data = Array.from(form.elements)
        .filter((input) => input.name)
        .reduce(
          (obj, input) => Object.assign(obj, { [input.name]: input.value }),
          {}
        );

      if (additionalData) {
        Object.assign(data, additionalData);
      }

      fetch(finalFormEndpoint, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => {
          // It's likely a spam/bot request, so bypass it to validate via captcha
          if (response.status === 422) {
            Object.keys(additionalData).forEach((key) => {
              const el = document.createElement("input");
              el.type = "hidden";
              el.name = key;
              el.value = injectedData[key];

              form.appendChild(el);
            });

            form.submit();
            throw new Error("Please finish the captcha challenge");
          }

          if (response.status !== 200) {
            throw new Error(response.statusText);
          }

          return response.json();
        })
        .then(() => {
          setMessage("We'll be in touch soon.");
          setStatus("success");
        })
        .catch((err) => {
          setMessage(err.toString());
          setStatus("error");
        });
    }
  };

  return { handleSubmit, status, message };
}

export default useForm;

See the React contact form guide for a complete guide how to implement HeroTofu forms backend.

 
You code frontend. We handle backend.Try Our Forms Backend