Click files to view code →
Build a form component with multiple input fields that includes real-time validation, error messages, and form submission handling. The form should validate user input and provide feedback before submission.
[!TIP] Goal
Use React's
useState[!IMPORTANT] Requirements
No external dependencies needed for basic validation.
Key Topics:
Plan of Action:
SimpleFormimport React, { useState } from 'react';
import './SimpleForm.css';
function SimpleForm() {
// Form data state
const [formData, setFormData] = useState({
fullName: '',
email: '',
password: '',
confirmPassword: '',
age: '',
terms: false
});
// Error state
const [errors, setErrors] = useState({});
// Form submission state
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitSuccess, setSubmitSuccess] = useState(false);
// Validation functions
const validateName = (name) => {
if (!name.trim()) {
return 'Name is required';
}
if (name.trim().length < 2) {
return 'Name must be at least 2 characters';
}
return '';
};
const validateEmail = (email) => {
if (!email) {
return 'Email is required';
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return 'Please enter a valid email address';
}
return '';
};
const validatePassword = (password) => {
if (!password) {
return 'Password is required';
}
if (password.length < 8) {
return 'Password must be at least 8 characters';
}
// ...CSS Styling (SimpleForm.css):
.form-container {
max-width: 500px;
margin: 2rem auto;
padding: 2rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
font-family: Arial, sans-serif;
}
.form-container h2 {
margin-top: 0;
color: #333;
text-align: center;
}
.simple-form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group label {
margin-bottom: 0.5rem;
font-weight: 600;
color: #333;
font-size: 0.875rem;
}
.required {
color: #f44336;
}
.form-group input[type="text"],
.form-group input[type="email"],
.form-group input[type="password"],
.form-group input[type="number"] {
padding: 0.75rem;
font-size: 1rem;
border: 2px solid #e0e0e0;
border-radius: 6px;
transition: border-color 0.2s ease;
outline: none;
}
// ...Best Practices:
Common Pitfalls:
Enhancements:
Advanced Version with Custom Hooks:
// useForm.js - Custom hook for form management
import { useState } from 'react';
export function useForm(initialValues, validationRules) {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState({});
const [touched, setTouched] = useState({});
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setValues(prev => ({
...prev,
[name]: type === 'checkbox' ? checked : value
}));
};
const handleBlur = (e) => {
const { name } = e.target;
setTouched(prev => ({ ...prev, [name]: true }));
if (validationRules[name]) {
const error = validationRules[name](values[name], values);
setErrors(prev => ({ ...prev, [name]: error }));
}
};
const validateAll = () => {
const newErrors = {};
Object.keys(validationRules).forEach(key => {
const error = validationRules[key](values[key], values);
if (error) newErrors[key] = error;
});
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const resetForm = () => {
setValues(initialValues);
setErrors({});
setTouched({});
};
return {
values,
errors,
touched,
handleChange,
handleBlur,
validateAll,
resetForm
// ...Testing Considerations:
Real-World Use Cases:
This form component demonstrates comprehensive form handling with validation and is production-ready for most use cases.
No files open
Click a file in the explorer to view