OneCompiler

reactform

104

import React, { useState } from 'react';

export default function App() {
const [formData, setFormData] = useState({ email: '', password: '' });
const [errors, setErrors] = useState({});
const [isLoggedIn, setIsLoggedIn] = useState(false);

const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
setErrors({}); // Clear errors on input
};

const validateForm = () => {
const newErrors = {};
const emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+$/;

if (!formData.email.trim()) {
  newErrors.email = 'Email is required';
} else if (!emailRegex.test(formData.email)) {
  newErrors.email = 'Invalid email format';
}

if (!formData.password) {
  newErrors.password = 'Password is required';
} else if (formData.password.length < 6) {
  newErrors.password = 'Password must be at least 6 characters';
}

return newErrors;

};

const handleSubmit = async (e) => {
e.preventDefault();
const validationErrors = validateForm();

if (Object.keys(validationErrors).length > 0) {
  setErrors(validationErrors);
  return;
}

// Submit using Fetch API
try {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(formData),
  });

  const result = await response.json();
  console.log('Fetch result:', result);

  setIsLoggedIn(true);
} catch (error) {
  console.error('Fetch error:', error);
}

};

return (
<div style={{ padding: '20px', fontFamily: 'Arial' }}>
{!isLoggedIn ? (
<>
<h2>Login</h2>
<form onSubmit={handleSubmit} noValidate>
<div>
<input type="email" name="email" placeholder="Email" value={formData.email} onChange={handleChange} required /><br />
{errors.email && <small style={{ color: 'red' }}>{errors.email}</small>}
</div>
<br />
<div>
<input type="password" name="password" placeholder="Password" value={formData.password} onChange={handleChange} required /><br />
{errors.password && <small style={{ color: 'red' }}>{errors.password}</small>}
</div>
<br />
<button type="submit">Login</button>
</form>
</>
) : (
<>
<h2>Dashboard</h2>
<p><strong>Email:</strong> {formData.email}</p>
<p><strong>Password:</strong> {formData.password}</p>
</>
)}
</div>
);
}