React Holiday

My Secret Weapon for Forms

I have a secret weapon for forms. It’s a one liner that returns an object from any properly labled form.

Object.fromEntries(new FormData(event.target));

We’ll spend our remaining days talking about forms. For now, I want you to know how FormData works.

Capture the <form>

Like all other events, form submit events can be captured and handled on-page.

<form
  onSubmit={(event) => {
    console.log(event);
  }}
/>

We also need to prevent the default behavior of a form which is to submit and redirect.

<form
  onSubmit={(event) => {
    event.preventDefault();
    console.log(event);
  }}
/>

Parse the <form>

With every event, we get the element that triggered it via event.target.

We can use that target element to create an object from the form data, using the FormData API and snippet above:

Object.fromEntries(new FormData(event.target));

Provided our form is properly coded, you’ll get a new key for every name attribute on your form.

Take it home

Open this CodeSandbox. You’ll find a minimal form that uses this approach to log form data as an object. Add a new input, submit button, or both! Notice how the object includes all new keys without additional intervention.