React Forms Submit
Handling form submission in React
📤 What is Form Submission?
Form submission in React involves handling the submit event, preventing default browser behavior, and processing form data. You can validate inputs, send data to servers, and provide user feedback all within your React component.
function LoginForm() {
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted!');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Login</button>
</form>
);
}
Output:
Form Submit Concepts
Prevent Default
Stop page reload
e.preventDefault();
Validation
Check data before submit
if (!email) {
return;
}
Data Processing
Handle form data
const data = {
name, email
};
Feedback
Show success/error
setMessage('Success!');
🔹 Basic Form Submit
The onSubmit handler is attached to the form element, not the button. Always call e.preventDefault() to stop the browser from reloading the page, which is the default form submission behavior.
import { useState } from 'react';
function ContactForm() {
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted email: ${email}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter email"
/>
<button type="submit">Submit</button>
</form>
);
}
Output:
🔹 Form with Validation
Validate form data before processing it. Check for empty fields, correct formats, or any business rules. Display error messages to guide users in correcting their input before submission.
function SignupForm() {
const [username, setUsername] = useState('');
const [error, setError] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// Validation
if (username.length < 3) {
setError('Username must be at least 3 characters');
return;
}
setError('');
alert('Form submitted successfully!');
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit">Sign Up</button>
</form>
);
}
Output:
🔹 Complete Form Example
A real-world form combines multiple inputs, validation, error handling, and success feedback. This example shows how to manage all form data in a single state object and validate multiple fields.
function RegistrationForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: ''
});
const [errors, setErrors] = useState({});
const [success, setSuccess] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
const newErrors = {};
if (!formData.name) newErrors.name = 'Name is required';
if (!formData.email) newErrors.email = 'Email is required';
if (formData.password.length < 6) {
newErrors.password = 'Password must be 6+ characters';
}
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
setErrors({});
setSuccess(true);
console.log('Form data:', formData);
};
return (
<form onSubmit={handleSubmit}>
<input name="name" value={formData.name}
onChange={handleChange} placeholder="Name" />
{errors.name && <p style={{ color: 'red' }}>{errors.name}</p>}
<input name="email" value={formData.email}
onChange={handleChange} placeholder="Email" />
{errors.email && <p style={{ color: 'red' }}>{errors.email}</p>}
<input name="password" type="password"
value={formData.password} onChange={handleChange}
placeholder="Password" />
{errors.password && <p style={{ color: 'red' }}>{errors.password}</p>}
<button type="submit">Register</button>
{success && <p style={{ color: 'green' }}>Registration successful!</p>}
</form>
);
}
Output:
🔹 Resetting Form After Submit
After successful submission, you often want to clear the form so users can submit again. Reset all state values to their initial empty state to provide a clean form for the next entry.
function FeedbackForm() {
const [feedback, setFeedback] = useState('');
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
console.log('Feedback:', feedback);
// Reset form
setFeedback('');
setSubmitted(true);
// Hide success message after 3 seconds
setTimeout(() => setSubmitted(false), 3000);
};
return (
<form onSubmit={handleSubmit}>
<textarea
value={feedback}
onChange={(e) => setFeedback(e.target.value)}
placeholder="Your feedback"
/>
<button type="submit">Send Feedback</button>
{submitted && <p style={{ color: 'green' }}>Thank you!</p>}
</form>
);
}