In this project, you will build a React application with form handling capabilities. You will create controlled components, implement form validation, and handle form submission effectively.
# Create a new React project npx create-react-app form-management-project # Install dependencies cd form-management-project npm install # Start the development server npm start
// Form Component import React, { useState } from 'react'; function RegistrationForm() { const [formData, setFormData] = useState({ username: '', email: '', password: '', confirmPassword: '', agreeToTerms: false }); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const handleChange = (e) => { const { name, value, type, checked } = e.target; setFormData({ ...formData, [name]: type === 'checkbox' ? checked : value }); }; const validateForm = () => { const newErrors = {}; // Validate username if (!formData.username.trim()) { newErrors.username = 'Username is required'; } // Validate email if (!formData.email.trim()) { newErrors.email = 'Email is required'; } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) { newErrors.email = 'Email is invalid'; } // Validate password if (!formData.password) { newErrors.password = 'Password is required'; } else if (formData.password.length < 6) { newErrors.password = 'Password must be at least 6 characters'; } // Validate confirm password if (formData.password !== formData.confirmPassword) { newErrors.confirmPassword = 'Passwords do not match'; } // Validate terms if (!formData.agreeToTerms) { newErrors.agreeToTerms = 'You must agree to the terms'; } return newErrors; }; const handleSubmit = (e) => { e.preventDefault(); const validationErrors = validateForm(); if (Object.keys(validationErrors).length === 0) { setIsSubmitting(true); // Simulate API call setTimeout(() => { console.log('Form submitted:', formData); setIsSubmitting(false); // Reset form after successful submission setFormData({ username: '', email: '', password: '', confirmPassword: '', agreeToTerms: false }); }, 1500); } else { setErrors(validationErrors); } }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="username">Username</label> <input type="text" id="username" name="username" value={formData.username} onChange={handleChange} /> {errors.username && <span className="error">{errors.username}</span>} </div> {/* Other form fields would go here */} <button type="submit" disabled={isSubmitting}> {isSubmitting ? 'Submitting...' : 'Register'} </button> </form> ); } export default RegistrationForm;