Programming & Development / April 19, 2025

How to Use formData.get() in React to Handle Form Input Values

React FormData example formData.get() React handle form submit React get form values in React React form input handling

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 });



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex