React

POST request mot Endpoint

Submit a Form Data to REST API in a React App

So let us start coding the React app.

Create a new React project

The first step is setting up a React application on your system. This can be easily done using the NPX tool.
So, first and create a react application using NPX. Don’t bother about the term NPX, because it’s a tool coming with NPM(Node Package Manager) 5.2+ onwards which will install on your system with Node.js itself.
If you need further assistance in the installation of React on your system, use the below links.
Install React on , , and

npx submit-form-data-rest-api-react

This command will create a react application with the project name submit-form-data-rest-api-react.
Now enter the project directory and start the app.

cd submit-form-data-rest-api-react
npm start

It will open up the React application we have created in our browser window with the address https://localhost:3000. The port may vary if 3000 is busy.

image.jpeg
Now we can use our favorite code editor to edit our project. I personally recommend .

Declare the states

We can see an App function inside the src/App.js file. Declare the states needed to store the input values, name, email, and mobile number.
Here, we are also declaring a state message to store the success or error message.
function App() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [mobileNumber, setMobileNumber] = useState("");
const [message, setMessage] = useState("");
...
}

Function to handle the submit action

When the form is submitted, it calls a function handleSubmit where it posts the data to a REST API.
We are using fetch to post the data to the a REST API. Here we are using the dummy REST API by httpbin.org and you can use the real API URL here.
Before passing the form data name, email and mobile number, we need to stringify it. JSON.stringify() function will take care of it.

let res = await fetch("https://httpbin.org/post", {
method: "POST",
body: JSON.stringify({
name: name,
email: email,
mobileNumber: mobileNumber,
}),
});

To get the response data in JSON format, we need to convert the original response.
Note that in our API, the response is not returning the created document from the backend. So we really not using the above step. But in general, we will get the created document from the backend and we need to convert it to JSON.
let resJson = await res.json();

So that the entire handleSubmit function will be the same as below.
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("https://httpbin.org/post", {
method: "POST",
body: JSON.stringify({
name: name,
email: email,
mobileNumber: mobileNumber,
}),
});

let resJson = await res.json();
if (res.status === 200) {
setName("");
setEmail("");
setMessage("User created successfully");
} else {
setMessage("Some error occured");
}
} catch (err) {
console.log(err);
}
};

Note: We usually get a status value as the response from the backend. status 200 refers to the success to the API call. This is why we coded if res.status === 200, display “User created successfully” message.

Code the View

Now let us code the view of our app. We use the JSX to code the view in React.
In our case, we are creating a form with 3 input fields, name, email and mobile number.
Any change in the input box will set the value to the state.
A submit button will call the function handleSubmit().
We will also code a portion to display the success or error message.
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
placeholder="Name"
onChange={(e) => setName(e.target.value)}
/>
<input
type="text"
value={email}
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="text"
value={mobileNumber}
placeholder="Mobile Number"
onChange={(e) => setMobileNumber(e.target.value)}
/>

<button type="submit">Create</button>

<div className="message">{message ? <p>{message}</p> : null}</div>
</form>
</div>
);

So that the complete App.js file will looks the same as below.
// src/App.js

import "./App.css";
import { useState } from "react";

function App() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [mobileNumber, setMobileNumber] = useState("");
const [message, setMessage] = useState("");

let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("https://httpbin.org/post", {
method: "POST",
body: JSON.stringify({
name: name,
email: email,
mobileNumber: mobileNumber,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setName("");
setEmail("");
setMessage("User created successfully");
} else {
setMessage("Some error occured");
}
} catch (err) {
console.log(err);
}
};

return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
placeholder="Name"
onChange={(e) => setName(e.target.value)}
/>
<input
type="text"
value={email}
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="text"
value={mobileNumber}
placeholder="Mobile Number"
onChange={(e) => setMobileNumber(e.target.value)}
/>

<button type="submit">Create</button>

<div className="message">{message ? <p>{message}</p> : null}</div>
</form>
</div>
);
}

export default App;

Add some styles (out of topic)

Let us also add some CSS in our app to make it a bit shinier. We are already importing the App.css file inside the App.js and so that we can add our CSS in this file.
// src/App.css

.App {
display: flex;
justify-content: center;
margin-top: 5rem;
}
input {
display: block;
width: 20rem;
height: 2rem;
padding: 0.5rem;
font-size: 1.1em;
font-weight: 500;
margin-bottom: 2rem;
}
button {
border: none;
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.