React Advanced

0% completed

Previous
Next
Understanding FormData in React

In this section, you will learn about forms — from collecting form data to optimistically updating form data on the client-side. By the end of this section, you will be able to handle and manipulate form data like a pro.

What is FormData?

When handling forms in React, sometimes you need to work with form data in a way that mimics how traditional HTML forms submit data. FormData is a built-in JavaScript API that allows you to construct key-value pairs representing form fields and their values.

When to Use FormData?

This API is particularly useful when:

  • Uploading files (images, documents, etc.).
  • Handling forms dynamically (adding/removing inputs).
  • Sending form data without relying on React state.

Creating and Submitting FormData in React

To use FormData, we typically retrieve form data from a <form> element or construct it manually.

Example

Let's look at a basic formData usage in React:

import { useRef } from "react"; function BasicFormData() { const formRef = useRef(null); const handleSubmit = (event) => { event.preventDefault(); // Create FormData object const formData = new FormData(formRef.current); // Log values for (let [key, value] of formData.entries()) { console.log(key, value); } }; return ( <form ref={formRef} onSubmit={handleSubmit}> <input type="text" name="username" placeholder="Enter your name" /> <input type="email" name="email" placeholder="Enter your email" /> <button type="submit">Submit</button> </form> ); } export default BasicFormData;

In this code example:

  • The form is referenced using useRef() with its initial value set to null.
  • A new instance of the FormData object is created from the form reference.
  • The .entries() method allows us to iterate over the form fields and log their values.

Handling File Uploads with FormData

FormData is widely used for handling file uploads in React applications.

Example

Let's look at an example of uploading a single file:

import { useState } from "react"; function FileUploadForm() { const [file, setFile] = useState(null); const handleFileChange = (event) => { setFile(event.target.files[0]); }; const handleSubmit = (event) => { event.preventDefault(); if (!file) { alert("Please select a file."); return; } const formData = new FormData(); formData.append("file", file); // Send data to server fetch("https://your-api.com/upload", { method: "POST", body: formData, }) .then((response) => response.json()) .then((data) => console.log("Success:", data)) .catch((error) => console.error("Error:", error)); }; return ( <form onSubmit={handleSubmit}> <input type="file" onChange={handleFileChange} /> <button type="submit">Upload</button> </form> ); } export default FileUploadForm;

In this code example:

  • We declare a file state to track files and set the intital state to null.
  • A new instance of the formData object is created
  • We use event.target.files[0] to retrieve the selected file.
  • formData.append("key", value) adds the file to FormData.
  • The fetch API sends the form data as multipart/form-data.

Uploading Multiple Files

To allow multiple file uploads, update the input field with multiple and iterate through the selected files.

Example

Let's look at an example of uploading multiple files:

import { useState } from "react"; function MultiFileUpload() { const [files, setFiles] = useState([]); const handleFileChange = (event) => { setFiles(event.target.files); }; const handleSubmit = (event) => { event.preventDefault(); if (files.length === 0) { alert("Please select files."); return; } const formData = new FormData(); for (let i = 0; i < files.length; i++) { formData.append("files", files[i]); } fetch("https://your-api.com/upload", { method: "POST", body: formData, }) .then((response) => response.json()) .then((data) => console.log("Success:", data)) .catch((error) => console.error("Error:", error)); }; return ( <form onSubmit={handleSubmit}> <input type="file" multiple onChange={handleFileChange} /> <button type="submit">Upload Files</button> </form> ); } export default MultiFileUpload;

In this code example:

  • We use the multiple attribute on the <input> to allow multiple file selection.
  • We looped through files to ensure that all files are appended.

Extracting and Manipulating FormData Values

After appending form fields to FormData, you can extract values using:

  • .get(name) – Gets a single value.
  • .getAll(name) – Gets all values with the same name.
  • .entries() – Iterates over all key-value pairs.
  • .keys() – Iterates over form field names.
  • .values() – Iterates over form field values.

Example: Extracting FormData Values

You can extract individual FormData values.

function ExtractFormData() { const handleSubmit = (event) => { event.preventDefault(); const formData = new FormData(event.target); // to extract single value console.log("Single value:", formData.get("username")); // to extract all values console.log("All values:", [...formData.entries()]); // to extract keys console.log("Keys:", [...formData.keys()]); // to extract values console.log("Values:", [...formData.values()]); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="username" placeholder="Username" /> <input type="email" name="email" placeholder="Email" /> <button type="submit">Submit</button> </form> ); } export default ExtractFormData;

In this example, we extracted different values from our FormData.

Handling FormData with Axios

You can handle FormData using Axios, a popular JavaScript library for making HTTP requests, typically used to fetch or send data to a server. It supports promises and can be used in both the browser and Node.js environments for tasks like AJAX requests and handling API calls.

Example

Let's look at an example that shows how to send FormData with Axios:

import axios from "axios"; function SubmitWithAxios() { const handleSubmit = (event) => { event.preventDefault(); const formData = new FormData(event.target); axios.post("https://your-api.com/upload", formData) .then(response => console.log("Success:", response.data)) .catch(error => console.error("Error:", error)); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="name" placeholder="Name" /> <input type="file" name="file" /> <button type="submit">Submit</button> </form> ); } export default SubmitWithAxios;

In this example:

  • The new instance of FormData object is being created from the form element that triggered the event, which is a form submission.
  • axios.post("https://your-api.com/upload", formData) sends the formData to the specified URL using a POST request. Axios.post then returns a promise.

Now that we have learned all about the FormData object and how to use it in our React forms, we'll move on to explore other form manipulations available in React.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next