javascript: getting to know formdata

2021-05-25

 | 

~2 min read

 | 

345 words

According to MDN:

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to “multipart/form-data”.

You can also pass it directly to the URLSearchParams constructor if you want to generate query parameters in the way a

would do if it were using simple GET submission.

I came across my first opportunity to use FormData in a React application recently where I was not using Formik, react-hook-form, etc.

Instead, we had a simple form:

import * as React from "react"

export default function MyForm() {
    return (
        <div className="form">
            <form>
                <h1>Form</h1>
                <label>
                    first
                    <input name="first name" />
                </label>
                <label>
                    last name
                    <input name="last-name" />
                </label>
                <label>
                    email
                    <input type="email" name="email" />
                </label>
                <button type="submit">submit</button>
            </form>
        </div>
    )
}

I wanted to add handling for the onSubmit event, and instead of having onChange handlers for each of the form fields which could then update a component state, I found that FormData worked quite well.

To use it, I added an onSubmit function and modified the <form> to be aware of it:

export default function MyForm() {
+     const onSubmit = (event) => {
+         event.preventDefault()
+         const data = new FormData(event.target)
+         const keys = data.keys()
+         const capturedKeys = []
+         for (const key of keys) {
+             console.log({ key })
+             capturedKeys.push(key)
+         }
+         // do whatever you want with capturedKeys
+     }

    return (
-         <div className="form" >
+         <div className="form" onSubmit={onSubmit}>
            // ...
        </div>
    )
}

In this way, I now have access to the form fields and can process them however I’d like without needing to import a library or do anything fancy. This is just a vanilla Javascript approach to form management and, at least in the simple cases, works quite well!

I also put together a small Code Sandbox to demonstrate how to use FormData.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!