Sometimes we might need to submit form data to a REST API in a web app. This is a simple article that explains the steps to submit form data to REST API in a React app.
If you are a visual learner, the YouTube video below is more suitable for you.
Prerequisites
Before continuing this article, you must learn the following technologies:-
- HTML
- JavaScript ES6
- React.js basics
What we will learn
In this article, we will learn to code a form in a React app. The form accepts some input fields and submitting it will post these data to an external REST API.
After completing, the app we will function the same as below.
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, install Node.js on your system 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 Windows, Ubuntu, and macOS
npx create-react-app 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.
Now we can use our favorite code editor to edit our project. I recommend Visual Studio Code.
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 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.
const resJson = await res.json();
So that the entire handleSubmit function will be the same as below.
const 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,
}),
});
const 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 of the API call. This is why we coded if res. status === 200, displaying a “User created successfully” message.
Code the View
Now let us code the view of our app. We use 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 look 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("");
const 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,
}),
});
const 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 to our app to make it a bit shinier. We are already importing the App.css file inside the App.js so that we can add our CSS to 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;
padding: 1rem;
width: 21.2rem;
font-size: 1.2em;
border-radius: 0.2rem;
cursor: pointer;
}
button:hover {
background-color: #c5c5c5;
}
.message {
font-size: 1.2em;
text-align: center;
color: #36a936;
}
Codesandbox
Refer to the CodeSandbox link to view the live app. You can clone this project to your CodeSandbox account and edit the code too.
https://codesandbox.io/s/musing-babbage-i5qoq
GitHub
You can always refer to the GitHub repository to clone this project, refer to the code, and work on top of it.
https://github.com/techomoro/submit-form-data-rest-api-react-demo-app
Summary
Here we discussed the steps to create a react app with a form UI that accepts some input values and the form submit action will call a REST API.
Thanks for this post – this is a clear example of how to submit form data from a React app. I was so frustrated today trying to figure out how to submit form data from my React client to my API and this lays it out clearly.
Good article
Nicely explained. The best part is the links to the project. Thanks a lot.
Excellent article, looking to use it on my website.
Thankyou