React.js login form:
- Captures
usernameandpassword. - Logs them to the console.
- Sends them to a sample login API (using
fetch).
You can plug this directly into your project.
import React, { useState } from "react";
export default function LoginForm() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
// 1. Show in console
console.log("Username:", username);
console.log("Password:", password);
try {
// 2. Call login API
const response = await fetch("https://example.com/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
throw new Error("Login failed");
}
const data = await response.json();
console.log("Login success:", data);
alert("Login successful!");
} catch (error) {
console.error("Error:", error);
alert("Login failed!");
}
};
return (
<div className="flex justify-center items-center h-screen bg-gray-100">
<form
onSubmit={handleSubmit}
className="bg-white shadow-md rounded-2xl p-6 w-80"
>
<h2 className="text-xl font-bold mb-4 text-center">Login</h2>
<div className="mb-4">
<label className="block text-sm font-medium">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="mt-1 w-full border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Enter username"
required
/>
</div>
<div className="mb-4">
<label className="block text-sm font-medium">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 w-full border rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="Enter password"
required
/>
</div>
<button
type="submit"
className="w-full bg-blue-600 text-white font-semibold py-2 rounded-lg hover:bg-blue-700 transition"
>
Login
</button>
</form>
</div>
);
}
🔑 How it works
- State hooks (
useState) track input values. - Form submit (
handleSubmit) prevents reload withe.preventDefault(). - Logs values to the console.
- Calls
fetch("https://example.com/api/login")with a POST request. - On success → logs API response, on error → shows alert.