0% completed
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.
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.
This API is particularly useful when:
To use FormData
, we typically retrieve form data from a <form>
element or construct it manually.
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:
useRef()
with its initial value set to null.FormData
object is created from the form reference..entries()
method allows us to iterate over the form fields and log their values.FormData
is widely used for handling file uploads in React applications.
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:
file
state to track files and set the intital state to null.formData
object is createdevent.target.files[0]
to retrieve the selected file.formData.append("key", value)
adds the file to FormData
.fetch
API sends the form data as multipart/form-data
.To allow multiple file uploads, update the input field with multiple
and iterate through the selected files.
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:
multiple
attribute on the <input>
to allow multiple file selection.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.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
.
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.
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:
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.
.....
.....
.....