File Upload With React Native

In this article, we are going to learn how to upload a file in React Native.

First, create react native app and open it.

For image upload, we use the expo-image-picker plugin and link with react native.

npm i expo-image-picker
react-native link expo-image-picker

To choose an image, we need to import ImagePicker from expo-image-picker.

import * as ImagePicker from 'expo-image-picker';

Now choose an image on the button click event and set them using the useState hook.

const [image, setImage] = useState(null);
const pickImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
     mediaTypes: ImagePicker.MediaTypeOptions.All,
     allowsEditing: true,
     aspect: [4, 3],
     quality: 1,
  });
  console.log(result);
  if (!result.cancelled) {
     setImage(result.uri);
  }
};

So, My file looks like this,

import React, { useState } from 'react';
import { Button, Image, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function App() {
  const [image, setImage] = useState(null);

  const pickImage = async () => {
     let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
     });
     console.log(result);
     if (!result.cancelled) {
        setImage(result.uri);
     }
  };

  return (
     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Button title="Pick an image from camera roll" onPress={pickImage} />
        {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
     </View>
  );
}

Output:-

Submit a Comment

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

Subscribe

Select Categories