Easier Form Handling with the FormData Interface

MDN Logo

The native browser API:s are evolving with speed and these days hide a lot of – potentially unknown – gems. One such gem is the FormData interface which has the potential to simplify form handling in your components.

In a modern context using React, forms tend to be “state heavy”. Typically inputs map to state handled by hooks like useState or useReducer with, at best, generic event handlers or complete form libraries like Formik are brought in.

Imagine a simple form to input your name.

Example: Simple name form
Example: Simple name form

FormData enables easy access to the data of the form à la:

var formElement = document.querySelector(formSelector);
var formData = Object.fromEntries(new FormData(formElement));

// formData now contains:
// {
//     "fname": "David",
//     "lname": "Banner"
// }

I will play around with this in future form contexts and imagine it will come in handy and likely reduce or completely remove some of the typical state management in form components.

Be the first to comment

Leave a Reply

Your email address will not be published.


*