SmartCodingTips

🔐 Login Form in React

A login form is a common UI component used to authenticate users. This example includes controlled inputs, basic validation, and a simulated login function.


🧱 1. Build the Login Form


import { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    setError('');
    setSuccess(false);

    if (!email || !password) {
      setError('All fields are required');
      return;
    }

    // Simulate API check
    if (email === 'admin@example.com' && password === 'admin123') {
      setSuccess(true);
    } else {
      setError('Invalid credentials');
    }
  };

  return (
    <form
      onSubmit={handleSubmit}
      className="max-w-md mx-auto bg-white dark:bg-gray-800 p-6 rounded shadow space-y-4"
    >
      <h2 className="text-2xl font-bold mb-4 text-center text-black dark:text-white">Login</h2>

      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        className="w-full px-4 py-2 border rounded dark:bg-gray-700 dark:text-white"
      />

      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        className="w-full px-4 py-2 border rounded dark:bg-gray-700 dark:text-white"
      />

      {error && <p className="text-red-500">{error}</p>}
      {success && <p className="text-green-500">Login successful!</p>}

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

export default LoginForm;

🚀 2. Use in App


import LoginForm from './LoginForm';

function App() {
  return (
    <main className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-800">
      <LoginForm />
    </main>
  );
}

export default App;

📋 Summary

  • Uses useState for form handling
  • Includes basic validation and error/success feedback
  • Simulates credential checking (can be replaced with real API)