In React Native, FormData is used when you need to send form-like data, such as file uploads or key-value pairs, typically in a POST request. It behaves similarly to how it works in the browser.
Here’s a basic example of how to use FormData in React Native:
Using a functional component with useState and filter method (Recommended for modern apps):
const sendFormData = async () => {
const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('email', 'john@example.com');
try {
const response = await fetch('https://your-api-url.com/endpoint', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error:', error);
}
};
Make sure the file object contains the correct structure:
const uploadImage = async () => {
const formData = new FormData();
// Replace this with your image picker result
const image = {
uri: 'file:///path/to/image.jpg',
name: 'image.jpg',
type: 'image/jpeg',
};
formData.append('photo', image);
formData.append('userId', '12345'); // you can send other data too
try {
const response = await fetch('https://your-api-url.com/upload', {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
// Add any other headers as needed (e.g., Authorization)
},
});
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Upload Error:', error);
}
};
If you want to send an array of items using FormData in React Native (e.g., a list of tags, multiple images, etc.), you can do it by appending each item individually with indexed or bracketed keys, depending on what the backend expects.
const uploadFormWithArray = async () => {
const formData = new FormData();
// Append a text field
formData.append('username', 'jaimin');
// Append an array of tags (as strings)
const tags = ['react', 'native', 'formdata'];
tags.forEach((tag, index) => {
formData.append(`tags[${index}]`, tag);
});
// Append an array of images
const images = [
{
uri: 'file:///path/to/image1.jpg',
name: 'image1.jpg',
type: 'image/jpeg',
},
{
uri: 'file:///path/to/image2.jpg',
name: 'image2.jpg',
type: 'image/jpeg',
},
];
images.forEach((image, index) => {
formData.append(`photos[${index}]`, image);
});
try {
const response = await fetch('https://your-api-url.com/upload', {
method: 'POST',
body: formData,
headers: {
// Content-Type should generally be left out for FormData
// 'Content-Type': 'multipart/form-data',
},
});
const result = await response.json();
console.log('Upload successful:', result);
} catch (error) {
console.error('Upload error:', error);
}
};
Work with our skilled React Native developers to accelerate your project and boost its performance.
Hire React Native Developers