Form Submission Basics with Uncontrolled Inputs
What you'll learn: How to handle form submissions and read uncontrolled input values using refs when the user submits.
The Core Pattern
With uncontrolled inputs, you don't track values during typing—you read them all at once when the form submits. This requires two key pieces:
- Prevent the default form behavior using
event.preventDefault()(otherwise the browser refreshes the page) - Read the ref values inside the submit handler to access what the user typed
Think of it like a comment card box: you don't peek at every card as people write them (no live tracking). Instead, you open the box and read all the cards when someone hits "submit" (reading refs on submit).
How It Works
import { useRef } from 'react';
function LoginForm() {
const emailRef = useRef(null);
const passwordRef = useRef(null);
function handleSubmit(event) {
event.preventDefault(); // Stop page refresh!
// Now read the values from the refs
const email = emailRef.current.value;
const password = passwordRef.current.value;
console.log('Submitted:', { email, password });
// Process your data here (API call, validation, etc.)
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
ref={emailRef}
defaultValue=""
/>
<input
type="password"
ref={passwordRef}
defaultValue=""
/>
<button type="submit">Log In</button>
</form>
);
}
The event.preventDefault() call is critical—without it, the browser performs its default form submission (page refresh), and you lose control of the process.
Key Takeaway: Handle uncontrolled form submissions by preventing default behavior with event.preventDefault(), then reading all ref values inside the submit handler to access user input all at once.