Course contentsShow
← React
Lesson 518 of 2,39614. Uncontrolled ComponentsFree lesson

Using FormData API with Uncontrolled Forms

Leverage the native FormData constructor to extract all form values without individual refs.

Using FormData API with Uncontrolled Forms

What you'll learn: How to extract all form values at once using the native FormData API, eliminating the need for individual refs for each input.

The Problem with Multiple Refs

In the previous lesson, you accessed multiple refs on submit—one useRef for each input. This works, but gets repetitive:

const nameRef = useRef(null);
const emailRef = useRef(null);
const ageRef = useRef(null);
// ... dozens more for larger forms

The FormData Solution

The native browser FormData constructor can extract all input values from a form at once, as long as each input has a name attribute:

function MyForm() {
  const handleSubmit = (event) => {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    
    const name = formData.get('username');
    const email = formData.get('email');
    
    console.log({ name, email });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" defaultValue="" />
      <input name="email" defaultValue="" />
      <button type="submit">Submit</button>
    </form>
  );
}

Key differences:

  • No refs needed
  • event.target is the form element itself
  • FormData reads the name attribute of each input
  • formData.get('fieldName') retrieves the value

Converting to an Object

You can convert all form data to a plain object:

const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
// { username: '...', email: '...' }

Key Takeaway: The FormData API lets you extract all uncontrolled form values in one line without managing individual refs, as long as your inputs have name attributes—perfect for simple, submit-only forms.