Skip to content
javascript

React + Axios POST request example

Apr 1, 2023Abhishek EH2 Min Read
React + Axios POST request example

In my previous article, I have written how to make POST requests in JavaScript using Axios. In this article, we will see how to do the same in React.

Project setup

Create a new react app using the following command:

1npx create-react-app react-axios-post

Install the axios library by running the below command:

1npm i axios

Add the following css in index.css:

index.css
1body {
2 display: flex;
3 justify-content: center;
4}
5.item {
6 display: flex;
7 justify-content: space-between;
8 gap: 20px;
9}

Creating the login form

Update the App.js with the following code:

App.js
1function App() {
2 return (
3 <div>
4 <form action="" id="login" method="post">
5 <h1>Login</h1>
6 <p className="item">
7 <label for="email"> Email </label>
8 <input type="email" name="email" id="email" />
9 </p>
10 <p className="item">
11 <label for="password"> Password </label>
12 <input type="password" name="password" id="password" />
13 </p>
14 <p className="item">
15 <input type="submit" value="Login" />
16 </p>
17 </form>
18 </div>
19 )
20}
21
22export default App

Here we have created a form with 2 fields: email and password. Also, we have a button to submit the form.

Handling the form submit

In the below code,

  • We are storing the email and password in their respective local states.
  • We have added a submit handler for the form, which calls the API endpoint using Axios with email and password in the request body.
App.js
1import axios from "axios"
2import { useState } from "react"
3
4function App() {
5 const handleSubmit = e => {
6 // Prevent the default submit and page reload
7 e.preventDefault()
8
9 // Handle validations
10 axios
11 .post("https://example.con/login", { email, password })
12 .then(response => {
13 console.log(response)
14 // Handle response
15 })
16 }
17
18 const [email, setEmail] = useState()
19 const [password, setPassword] = useState()
20 return (
21 <div>
22 <form action="" id="login" method="post" onSubmit={handleSubmit}>
23 <h1>Login</h1>
24 <p className="item">
25 <label for="email"> Email </label>
26 <input
27 type="email"
28 name="email"
29 id="email"
30 value={email}
31 onChange={e => setEmail(e.target.value)}
32 />
33 </p>
34 <p className="item">
35 <label for="password"> Password </label>
36 <input
37 type="password"
38 name="password"
39 id="password"
40 value={password}
41 onChange={e => setPassword(e.target.value)}
42 />
43 </p>
44 <p className="item">
45 <input type="submit" value="Login" />
46 </p>
47 </form>
48 </div>
49 )
50}
51
52export default App

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com