Task: Create a login form in React and send the data to a backend using fetch or axios.
β
Step-by-Step Login Form in React (Using fetch)
πΉ LoginForm.jsx
import React, { useState } from 'react';
function LoginForm() {
const [formData, setFormData] = useState({ email: '', password: '' });
const [message, setMessage] = useState('');
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:5000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const data = await response.json();
if (response.ok) {
setMessage(`β
Login successful: ${data.message}`);
} else {
setMessage(`β ${data.error || 'Login failed'}`);
}
} catch (error) {
setMessage('β Network error');
}
};
return (
<form onSubmit={handleSubmit} style={{ maxWidth: 300, margin: 'auto' }}>
<h2>Login</h2>
<input
type="email"
name="email"
placeholder="Email"
value={formData.email}
onChange={handleChange}
required
style={{ display: 'block', width: '100%', marginBottom: 10 }}
/>
<input
type="password"
name="password"
placeholder="Password"
value={formData.password}
onChange={handleChange}
required
style={{ display: 'block', width: '100%', marginBottom: 10 }}
/>
<button type="submit">Login</button>
{message && <p>{message}</p>}
</form>
);
}
export default LoginForm;
πΉ Sample Backend (Node.js + Express)
// server.js
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.json());
app.post('/api/login', (req, res) => {
const { email, password } = req.body;
if (email === 'admin@example.com' && password === '123456') {
res.status(200).json({ message: 'Welcome back!' });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
app.listen(5000, () => console.log('Server running on http://localhost:5000'));
π Notes:
- Ensure CORS is enabled on the backend for local development.
- You can also use
axiosinstead offetch. - In real projects, use HTTPS, JWTs, and secure password handling.