DEV Community

Cover image for React + Axios POST request example
collegewap
collegewap

Posted on • Edited on • Originally published at codingdeft.com

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:

npx create-react-app react-axios-post
Enter fullscreen mode Exit fullscreen mode

Install the axios library by running the below command:

npm i axios
Enter fullscreen mode Exit fullscreen mode

Add the following css in index.css:

body {
  display: flex;
  justify-content: center;
}
.item {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Creating the login form

Update the App.js with the following code:

function App() {
  return (
    <div>
      <form action="" id="login" method="post">
        <h1>Login</h1>
        <p className="item">
          <label for="email"> Email </label>
          <input type="email" name="email" id="email" />
        </p>
        <p className="item">
          <label for="password"> Password </label>
          <input type="password" name="password" id="password" />
        </p>
        <p className="item">
          <input type="submit" value="Login" />
        </p>
      </form>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

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.
import axios from "axios"
import { useState } from "react"

function App() {
  const handleSubmit = e => {
    // Prevent the default submit and page reload
    e.preventDefault()

    // Handle validations
    axios
      .post("https://example.con/login", { email, password })
      .then(response => {
        console.log(response)
        // Handle response
      })
  }

  const [email, setEmail] = useState()
  const [password, setPassword] = useState()
  return (
    <div>
      <form action="" id="login" method="post" onSubmit={handleSubmit}>
        <h1>Login</h1>
        <p className="item">
          <label for="email"> Email </label>
          <input
            type="email"
            name="email"
            id="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
          />
        </p>
        <p className="item">
          <label for="password"> Password </label>
          <input
            type="password"
            name="password"
            id="password"
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
        </p>
        <p className="item">
          <input type="submit" value="Login" />
        </p>
      </form>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mariaalba profile image
Maria

import { useState } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
import { Link, useNavigate } from 'react-router';

export default function Signup() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();

const handleSignup = async () => {

if (!name.trim() || !email.trim() || !password.trim()) {
  Swal.fire('Error', 'Please fill in all fields.', 'error');
  return;
}

if (name.trim().length < 5) {
  Swal.fire('Error', 'Name must be at least 5 characters long.', 'error');
  return;
}

if (password.trim().length < 8) {
  Swal.fire('Error', 'Password must be at least 8 characters long.', 'error');
  return;
}

try {
  await axios.post('api url', {
    name,
    email,
    password,
  });

  Swal.fire('Success', 'Account created successfully!', 'success').then(() => {
    navigate('/signin');
  });
} catch  {
  Swal.fire('Error', 'Registration failed. Try again.', 'error');
}
Enter fullscreen mode Exit fullscreen mode

};

return (


Full Name
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Full Name"
className='border-1 rounded-2xl w-80 p-2'
/>
      <label>Email Address</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Email Address"
              className='border-1 rounded-2xl w-80 p-2'
            />

     <label>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Password"
              className='border-1 rounded-2xl w-80 p-2'
            />

            <button
               onClick={handleSignup}
               className="btn btn-soft btn-accent"> Sign Up </button>


          <div className="mt-4 text-sm text-gray-600"> Already have an account?
            <Link to="/signin"><button className="btn btn-soft btn-primary">Sign In</button></Link>
         </div>

</div>

);
}

Collapse
 
marlo-bb profile image
ِMarlo Ber

import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate, Link } from 'react-router-dom';
import Swal from 'sweetalert2';

function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const apiUrl = '683da3f6199a0039e9e64a3e.mockapi.i...';

const btnLogin = async (e) => {
    e.preventDefault();

    if (!email || !password) {
        Swal.fire("Error", "Please fill in all fields", "error");
        return;
    }

    try {

        const res = await axios.get(apiUrl);
        const user = res.data.find(u => u.email === email);

        if (!user) {
            Swal.fire( "Email not found");
            return;
        }

        if (user.password !== password) {
            Swal.fire( "Incorrect password");
            return;
        }
        Swal.fire( "Login successful");
        localStorage.setItem("user", JSON.stringify(user));
        navigate("/");
    } catch (err) {
        console.error(err);
        Swal.fire( "Something went wrong. Please try again.");
    }
};

return (
    <div className="flex justify-center items-center min-h-screen">
        <div className="w-full max-w-md p-6 bg-white rounded shadow">
            <div className="text-center mb-6">
                <img src="" alt="Logo" className="mx-auto mb-4" />
                <h2 className="text-2xl font-bold">تسجيل الدخول</h2>
            </div>

            <form onSubmit={btnLogin} className="space-y-4">
                <div>
                    <label className="block mb-1">Email</label>
                    <input
                        type="email"
                        value={email}
                        placeholder="Email Address"
                        onChange={(e) => setEmail(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <div>
                    <label className="block mb-1">Password</label>
                    <input
                        type="password"
                        value={password}
                        placeholder="Password"
                        onChange={(e) => setPassword(e.target.value)}
                        className="w-full px-4 py-2 border rounded"
                        required
                    />
                </div>

                <button
                    type="submit"
                    className="w-full bg-blue-500 text-white py-2 rounded hover:bg-blue-600 transition"
                >
                    Login
                </button>
            </form>

            <div className="mt-4 text-center">
                <p>Don't have an account? <Link to="/register" className="text-red-500 hover:underline">Register</Link></p>
            </div>
        </div>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

}

export default Login;