Topic 24 of 54
Basic Form Submission
Overview
Submitting a form in React involves listening to the `<form>` element's `onSubmit` event, rather than putting an `onClick` on a button. This ensures that the form can be submitted by hitting 'Enter' on the keyboard. It's crucial to prevent the browser's default behavior, which is to refresh the entire page upon submission.
Syntax
`e.preventDefault()` is mandatory. If the page reloads, all your React state is instantly wiped out.
Handling the Submit Event
jsx
function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = (e) => {
// 1. MUST DO THIS FIRST: Prevents page reload
e.preventDefault();
// 2. Validate data
if (!email || !password) {
alert("Please fill all fields");
return;
}
// 3. Process data (e.g., API call)
console.log("Submitting:", { email, password });
// 4. Clear the form (optional)
setEmail("");
setPassword("");
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
{/* Must be type="submit" or omitted (it's the default inside a form) */}
<button type="submit">Log In</button>
</form>
);
}Common Pitfalls
- Putting the submit handler on the button's `onClick` instead of the form's `onSubmit`.
- Forgetting `e.preventDefault()`, resulting in a full page refresh that destroys your app state.
Interview Tips
- Always attach the handler to `onSubmit` on the `<form>`, never `onClick` on the submit button. This ensures accessibility and proper keyboard support (Enter key).
Real-World Example
Managing a 'loading' state while the form submits data to a backend API.
example
jsx
function ContactForm() {
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
try {
await api.submitContactForm(formData);
alert("Message sent!");
} catch (error) {
alert("Failed to send: " + error.message);
} finally {
setIsSubmitting(false); // Re-enable button
}
};
return (
<form onSubmit={handleSubmit}>
{/* Form fields... */}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Sending...' : 'Send Message'}
</button>
</form>
);
}