🔐 React Login Form Example
In this example, we’ll build a simple login form using controlled components. It includes input handling, validation, and submission handling.
🧱 Step-by-Step Code
import React, { useState } from 'react';
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (!email || !password) {
setError("All fields are required.");
return;
}
if (password.length < 6) {
setError("Password must be at least 6 characters.");
return;
}
setError('');
console.log("Logging in with", email, password);
// Send data to backend or redirect
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block mb-1 font-medium">Email</label>
<input
type="email"
className="w-full px-3 py-2 border rounded"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div>
<label className="block mb-1 font-medium">Password</label>
<input
type="password"
className="w-full px-3 py-2 border rounded"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error && <p className="text-red-600">{error}</p>}
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
>
Login
</button>
</form>
);
}
export default LoginForm;
✨ Key Concepts
- ✅ Controlled components with
useState() - ✅ Input validation with simple conditions
- ✅ Submit handler with
preventDefault() - ✅ Error display with conditional rendering
This is the foundation for login or authentication forms. For production apps, you'll typically add server requests and token handling.