Accessing Multiple Refs on Submit
What you'll learn: How to read values from several uncontrolled inputs at once when a form is submitted, using multiple useRef hooks.
When you have a form with multiple uncontrolled inputs, you need a separate ref for each one. Think of refs like labeled drawers—each input gets its own drawer, and when the form submits, you open all the drawers at once to collect what's inside.
The Pattern
Create one useRef per input field, attach each ref to its corresponding input element, and then access all the values in your submit handler:
import { useRef } from 'react';
function RegistrationForm() {
const usernameRef = useRef(null);
const emailRef = useRef(null);
const passwordRef = useRef(null);
function handleSubmit(event) {
event.preventDefault();
const username = usernameRef.current.value;
const email = emailRef.current.value;
const password = passwordRef.current.value;
console.log({ username, email, password });
// Send to API, validate, etc.
}
return (
<form onSubmit={handleSubmit}>
<input ref={usernameRef} defaultValue="" placeholder="Username" />
<input ref={emailRef} defaultValue="" placeholder="Email" />
<input ref={passwordRef} type="password" defaultValue="" placeholder="Password" />
<button type="submit">Register</button>
</form>
);
}
Why This Works
Each useRef creates an independent reference container. When you attach them to different inputs, you're creating direct connections to each DOM element. On submit, you simply read .current.value from each ref to gather all the form data in one place.
This approach keeps your component lightweight—no re-renders as the user types, but you still get all the values exactly when you need them.
Key Takeaway: Use multiple useRef hooks (one per input) and access their .current.value properties in your submit handler to collect all form data from uncontrolled components at once.