Hackforge Academy

Category: react

login form in react

Published on 02 Apr 2026

Explanation

Create a basic React functional component with useState hooks to store username and password values

Code:

import React, { useState } from "react";

function Login() {
  const [username, setUsername] = 
useState("");
  const [password, setPassword] =
 useState("");

  return <div>Login Form</div>;
}

export default Login;

Explanation

Add input fields for username and password and bind them with state using onChange handlers.

Code:

<form>
    <input type="text" 
      value={username}
      onChange={(e) => setUsername(
e.target.value)}
    />

    <input type="password"
      placeholder="Enter password"
      value={password}
      onChange={(e) => setPassword(
e.target.value
)}
    />
    <button type="submit">Login</button>
  </form>

Explanation

Add validation logic to check whether username and password fields are empty before calling the API.

Code:

const [error, setError] = useState("");

const handleSubmit = (e) => {
  e.preventDefault();

  if (!username || !password) {
    setError("All fields are required");
    return;
  }

  loginUser();
};

Explanation

Call the REST API using fetch method and send username and password in JSON format to backend server.

Code:

const loginUser = async () => {
  const response = await fetch("
http://localhost:8080/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ username, 
password })
  });

  const data = await response.json();
  console.log(data);
};

Explanation

Attach handleSubmit function to form submission and display validation error message if inputs are empty.

Code:

<form onSubmit={handleSubmit}>
    <input
      type="text"
      onChange={(e) => setUsername(
e.target.value)}
    />

    <input
      type="password"
      onChange={(e) => setPassword(
e.target.value)}
    />

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

    {error && <p style={{ color: "red" }}>
{error}</p>}
  </form>
);

Explanation

Complete React login component combining state management, validation, and REST API call in one working example.

Code:

import React, { useState } from "react";

function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const loginUser = async () => {
    const response = await fetch("http://localhost:8080/api/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ username, password })
    });

    const data = await response.json();
    console.log(data);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!username || !password) {
      setError("All fields are required");
      return;
    }

    setError("");
    loginUser();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Enter username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />

      <input
        type="password"
        placeholder="Enter password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />

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

      {error && <p style={{ color: "red" }}>{error}</p>}
    </form>
  );
}

export default Login;

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community