Categories
JavaScript Answers React Native Answers

How to use FormData in React Native?

Spread the love

Sometimes, we want to use FormData in React Native.

In this article, we’ll look at how to use FormData in React Native.

How to use FormData in React Native?

To use FormData in React Native, we can use the FormData constructor.

For instance, we write:

import * as React from 'react';
import { View, Button } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const submit = async () => {
    const formData = new FormData();
    formData.append('title', 'title');
    formData.append('content', 'content');
    fetch('https://jsonplaceholder.typicode.com', {
      body: formData,
      method: 'POST'
    });
  };

  return (
    <View>
      <Button title="submit" onPress={submit} />
    </View>
  );
}

to define the submit function that creates a FormData instance.

Then we call append with the key and value to add form data entries.

Next, we call fetch with the URL to make the request to and an object with the body set to the formData request body and the request method.

We set the onPress prop of the Button to call submit when we press the button

Conclusion

To use FormData in React Native, we can use the FormData constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *