React Post Form Data to API

Utilize React hooks and send data to any API endpoint

Forms Example
Using NextJS/TypeScript? Check out the NextJS form guide.

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.

Add the `herotofu-react` package

To effortlessly handle form submissions, you can use the herotofu-react package. It will do all the form submission process work for you.

npm install --save herotofu-react

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 { useFormData } from 'herotofu-react';

const Form = () => {
  // TODO - update to the correct endpoint
  const { formState, getFormSubmitHandler } = useFormData('https://herotofu.com/start');

  return (
    <>
      {!!formState.status && <div className="py-2">Current form status is: {formState.status}</div>}
      <form onSubmit={getFormSubmitHandler()}>
        <div className="pt-0 mb-3">
          <input
            type="text"
            placeholder="Your name"
            name="name"
            className="focus:outline-none focus:ring relative w-full px-3 py-3 text-sm text-gray-600 placeholder-gray-400 bg-white border-0 rounded shadow outline-none"
            required
          />
        </div>
        <div className="pt-0 mb-3">
          <input
            type="email"
            placeholder="Email"
            name="email"
            className="focus:outline-none focus:ring relative w-full px-3 py-3 text-sm text-gray-600 placeholder-gray-400 bg-white border-0 rounded shadow outline-none"
            required
          />
        </div>
        <div className="pt-0 mb-3">
          <textarea
            placeholder="Your message"
            name="message"
            className="focus:outline-none focus:ring relative w-full px-3 py-3 text-sm text-gray-600 placeholder-gray-400 bg-white border-0 rounded shadow outline-none"
            required
          />
        </div>
        <div className="pt-0 mb-3">
          <button
            className="active:bg-blue-600 hover:shadow-lg focus:outline-none px-6 py-3 mb-1 mr-1 text-sm font-bold text-white uppercase transition-all duration-150 ease-linear bg-blue-500 rounded shadow outline-none"
            type="submit"
          >
            Send a message (simple)
          </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: Send JSON data instead

You can also utilize the useJsonData hook to send JSON data instead of form data. This is useful when you want to send data to an API that requires a JSON payload and maybe don't want to use a form. The usage is similar to useFormData.

import { useJsonData } from 'herotofu-react';

function SendUserDataComponent({ userName, userEmail }: { userName: string; userEmail: string }) {
  const { dataState, sendData } = useJsonData('ANY_API_ENDPOINT_OR_HEROTOFU_FORM_ID');

  const onSubmitCallback = ({ status, data }) => {
    console.log(`The data was sent with status: ${status} and data: ${JSON.stringify(data)}`);
  };

  const handleButtonClick = () => {
    sendData(onSubmitCallback, { userName, userEmail });
  };

  return (
    <div>
      <h1>Welcome!</h1>
      <div style={{ margin: '1rem 0', fontSize: '2rem' }}>
        {dataState.status === 'success' && 'Done, email was sent!'}
        {dataState.status === 'error' && dataState.error.message}
        {dataState.status === 'loading' && 'Email is being sent now...'}
      </div>
      <div style={{ margin: '1rem 0' }}>
        <button onClick={handleButtonClick}>Click here to send user data</button>
      </div>
    </div>
  );
}

// Later in your code, render this component as:
<SendUserDataComponent userName="Joe Bloggs" userEmail="joe.bloggs@example.com" />

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