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.

1npm 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.

1import { useFormData } from 'herotofu-react';
2
3const Form = () => {
4  // TODO - update to the correct endpoint
5  const { formState, getFormSubmitHandler } = useFormData('https://herotofu.com/start');
6
7  return (
8    <>
9      {!!formState.status && <div className="py-2">Current form status is: {formState.status}</div>}
10      <form onSubmit={getFormSubmitHandler()}>
11        <div className="pt-0 mb-3">
12          <input
13            type="text"
14            placeholder="Your name"
15            name="name"
16            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"
17            required
18          />
19        </div>
20        <div className="pt-0 mb-3">
21          <input
22            type="email"
23            placeholder="Email"
24            name="email"
25            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"
26            required
27          />
28        </div>
29        <div className="pt-0 mb-3">
30          <textarea
31            placeholder="Your message"
32            name="message"
33            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"
34            required
35          />
36        </div>
37        <div className="pt-0 mb-3">
38          <button
39            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"
40            type="submit"
41          >
42            Send a message (simple)
43          </button>
44        </div>
45      </form>
46    </>
47  );
48};
49
50export 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
1import logo from "./logo.svg";
2import "./App.css";
3import { useEffect } from "react";
4import Form from "./Form";
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          <Form />
25        </div>
26      </header>
27    </div>
28  );
29}
30
31export 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.

1import { useJsonData } from 'herotofu-react';
2
3function SendUserDataComponent({ userName, userEmail }: { userName: string; userEmail: string }) {
4  const { dataState, sendData } = useJsonData('ANY_API_ENDPOINT_OR_HEROTOFU_FORM_ID');
5
6  const onSubmitCallback = ({ status, data }) => {
7    console.log(`The data was sent with status: ${status} and data: ${JSON.stringify(data)}`);
8  };
9
10  const handleButtonClick = () => {
11    sendData(onSubmitCallback, { userName, userEmail });
12  };
13
14  return (
15    <div>
16      <h1>Welcome!</h1>
17      <div style={{ margin: '1rem 0', fontSize: '2rem' }}>
18        {dataState.status === 'success' && 'Done, email was sent!'}
19        {dataState.status === 'error' && dataState.error.message}
20        {dataState.status === 'loading' && 'Email is being sent now...'}
21      </div>
22      <div style={{ margin: '1rem 0' }}>
23        <button onClick={handleButtonClick}>Click here to send user data</button>
24      </div>
25    </div>
26  );
27}
28
29// Later in your code, render this component as:
30<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.

Notice

We and selected third parties collect personal information as specified in the privacy policy and use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.

Use the “Accept” button to consent. Use the “Reject” button or close this notice to continue without accepting.