When building forms in React, you may need a quick way to access form input values. The FormData
API provides a convenient way to do that โ especially with formData.get()
. This guide shows how to use it in a modern React component.
๐ ๏ธ React Example: Using formData.get()
jsx
import React from 'react';
const MyForm = () => {
const handleSubmit = (event) => {
event.preventDefault();
// Create a FormData object using the form element
const formData = new FormData(event.target);
// Get individual form field values
const name = formData.get('name');
const email = formData.get('email');
// Log or handle the values
console.log('Name:', name);
console.log('Email:', email);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" name="name" required />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" required />
</div>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
๐ง How It Works
โ
1. event.preventDefault()
Prevents the default page reload behavior during form submission so you can handle it in React.
โ
2. new FormData(event.target)
Creates a FormData object using the form DOM element (event.target
refers to the form).
โ
3. formData.get('name')
Fetches the value of the form field with name="name"
. Same for email
.
โ
4. Use the Values
You can:
- Log them
- Store them in state
- Send them via API
๐ฆ Why Use FormData
in React?
- โ
Easy to retrieve form values
- โ
Works well for file uploads
- โ
Useful when you're not binding each field to state (e.g., quick-and-dirty forms or dynamic inputs)
โ ๏ธ Pro Tips:
- Ensure your inputs have matching
name
attributes. formData.get()
returns a File
object for file inputs.- Use
formData.entries()
to iterate through all form fields. - Great for forms without controlled components.
๐งช Optional: Add State Sync (if needed)
jsx
const [formValues, setFormValues] = useState({ name: '', email: '' });
setFormValues({ name, email });