Example of Image Picker in React Native

React Native Image Picker

Here is an example of Image Picker in React Native. For picking the image we will use a very good library called react-native-image-picker. It is a React Native module that allows you to select a photo/video from the device library or camera. It is very simple and straight forward.

You have so many options while choosing the image/video like you can decide the maxWidth and maxHeight if the image, you can set the quality of the image/video using quality (0-1), videoQuality(low-high), in case you want to use it to record video then you can set the video max duration in seconds, also you will have the option to saves the image/video file captured to public photos.

A new version of React Native Image Picker is out. We have updated the post for latest V3.+ version also.

How to Use ImagePicker Component?

Before the last major update in  library (Major update: V 3.+)

react-native-image-picker library provided an ImagePicker component in which you can set the options like the title of the picker, Your custom Buttons(Name and title of the button) and storage options like skipBackup or path.
Here is the code snippet of ImagePicker we have used in this Example

var options = {
   title: 'Select Image',
   customButtons: [
     {
       name: 'customOptionKey',
       title: 'Choose Photo from Custom Option'
     },
   ],
   storageOptions: {
     skipBackup: true,
     path: 'images',
   },
};
ImagePicker.showImagePicker(options, response => {
   console.log('Response = ', response);
   if (response.didCancel) {
     console.log('User cancelled image picker');
   } else if (response.error) {
     console.log('ImagePicker Error: ', response.error);
   } else if (response.customButton) {
     console.log(
       'User tapped custom button: ',
       response.customButton
     );
     alert(response.customButton);
   } else {
     setFilePath(response);
   }
});

But now after version 3.+

You will have different API to access the images/video, You can now

  1. Click images
  2. Record Videos
  3. Pick Images
  4. Pick Videos

Now we have two different APIs launchCamera and launchImageLibrary. This is very easy to use and works perfectly for Android and iOS both.

Image Picker Example Description

In this example below, we will have 4 different buttons on a screen and on click of each button user can

  1. Click image and captured image path will be returned
  2. Record video and recorded video path will be returned
  3. Pick image from gallery
  4. Pick video from gallery

So Let’s get started with our Example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use ImagePicker we need to install react-native-image-picker dependency.

To install this open the terminal and jump into your project using

cd ProjectName

Run the following command

npm install react-native-image-picker --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module the directory named react-native-image-picker.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use

cd ios && pod install && cd ..

Android Permission to use the Camera and to Read the Storage

We are using a Native API Camera and also going to choose the image from the gallery so we need to add some permission to the AndroidManifest.xml file.

Please add the following permissions in the AndroidManifest.xml

<uses-permission
  android:name="android.permission.CAMERA"
/>
<uses-permission
  android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
Permission Purpose
CAMERA To access the camera
WRITE_EXTERNAL_STORAGE To Read and Write the content in the SD card


For more about the permission, you can see this post.

IOS Permission to use the Camera and to Read the Storage

1. Open the project ImagePickerExample -> ios -> ImagePickerExample.xcodeproj in XCode. Click on Project (ImagePickerExample in my case) from the left sidebar and you will see multiple options in the workspace.

2. Select info tab which is info.plist

3. Click on the plus button to add following permission key and value which will be visible when permission dialog pops up.

  • If you are allowing user to select image/video from photos, add “Privacy – Photo Library Additions Usage Description”.
  • To capture image add “Privacy – Camera Usage Description”.
  • If you are allowing user to capture video add “Privacy – Camera Usage Description” add “Privacy – Microphone Usage Description”.
Key Value
Privacy – Photo Library Additions Usage Description App needs photo library Access
Privacy – Camera Usage Description App needs Camera Access Permission for testing
Privacy – Microphone Usage Description App needs Microphone Access Permission for testing

Code for Image Picker in React Native (Image Picker V2.+)

Open App.js in any code editor and replace the code with the following code

App.js

// Example of Image Picker in React Native
// https://aboutreact.com/example-of-image-picker-in-react-native/

// Import React
import React, {useState} from 'react';
// Import required components
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
} from 'react-native';

// Import Image Picker
import ImagePicker from 'react-native-image-picker';

const App = () => {
  const [filePath, setFilePath] = useState({});

  const chooseFile = () => {
    let options = {
      title: 'Select Image',
      customButtons: [
        {
          name: 'customOptionKey',
          title: 'Choose Photo from Custom Option'
        },
      ],
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };
    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log(
          'User tapped custom button: ',
          response.customButton
        );
        alert(response.customButton);
      } else {
        let source = response;
        // You can also display the image using data:
        // let source = {
        //   uri: 'data:image/jpeg;base64,' + response.data
        // };
        setFilePath(source);
      }
    });
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <Text style={styles.titleText}>
        Example of Image Picker in React Native
      </Text>
      <View style={styles.container}>
        {/*<Image 
          source={{ uri: filePath.path}} 
          style={{width: 100, height: 100}} />*/}
        <Image
          source={{
            uri: 'data:image/jpeg;base64,' + filePath.data,
          }}
          style={styles.imageStyle}
        />
        <Image
          source={{uri: filePath.uri}}
          style={styles.imageStyle}
        />
        <Text style={styles.textStyle}>
          {filePath.uri}
        </Text>
        {/*
          <Button
            title="Choose File"
            onPress={chooseFile} />
        */}
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={chooseFile}>
          <Text style={styles.textStyle}>
            Choose Image
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  titleText: {
    fontSize: 22,
    fontWeight: 'bold',
    textAlign: 'center',
    paddingVertical: 20,
  },
  textStyle: {
    padding: 10,
    color: 'black',
  },
  buttonStyle: {
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#DDDDDD',
    padding: 5,
  },
  imageStyle: {
    width: 200,
    height: 200,
    margin: 5,
  },
});

Code for Image Picker in React Native (Image Picker V3.+)

Open App.js in any code editor and replace the code with the following code

App.js

// Example of Image Picker in React Native
// https://aboutreact.com/example-of-image-picker-in-react-native/

// Import React
import React, {useState} from 'react';
// Import required components
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Image,
  Platform,
  PermissionsAndroid,
} from 'react-native';

// Import Image Picker
// import ImagePicker from 'react-native-image-picker';
import {
  launchCamera,
  launchImageLibrary
} from 'react-native-image-picker';

const App = () => {
  const [filePath, setFilePath] = useState({});

  const requestCameraPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: 'Camera Permission',
            message: 'App needs camera permission',
          },
        );
        // If CAMERA Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        return false;
      }
    } else return true;
  };

  const requestExternalWritePermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'External Storage Write Permission',
            message: 'App needs write permission',
          },
        );
        // If WRITE_EXTERNAL_STORAGE Permission is granted
        return granted === PermissionsAndroid.RESULTS.GRANTED;
      } catch (err) {
        console.warn(err);
        alert('Write permission err', err);
      }
      return false;
    } else return true;
  };

  const captureImage = async (type) => {
    let options = {
      mediaType: type,
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
      videoQuality: 'low',
      durationLimit: 30, //Video max duration in seconds
      saveToPhotos: true,
    };
    let isCameraPermitted = await requestCameraPermission();
    let isStoragePermitted = await requestExternalWritePermission();
    if (isCameraPermitted && isStoragePermitted) {
      launchCamera(options, (response) => {
        console.log('Response = ', response);

        if (response.didCancel) {
          alert('User cancelled camera picker');
          return;
        } else if (response.errorCode == 'camera_unavailable') {
          alert('Camera not available on device');
          return;
        } else if (response.errorCode == 'permission') {
          alert('Permission not satisfied');
          return;
        } else if (response.errorCode == 'others') {
          alert(response.errorMessage);
          return;
        }
        console.log('base64 -> ', response.base64);
        console.log('uri -> ', response.uri);
        console.log('width -> ', response.width);
        console.log('height -> ', response.height);
        console.log('fileSize -> ', response.fileSize);
        console.log('type -> ', response.type);
        console.log('fileName -> ', response.fileName);
        setFilePath(response);
      });
    }
  };

  const chooseFile = (type) => {
    let options = {
      mediaType: type,
      maxWidth: 300,
      maxHeight: 550,
      quality: 1,
    };
    launchImageLibrary(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        alert('User cancelled camera picker');
        return;
      } else if (response.errorCode == 'camera_unavailable') {
        alert('Camera not available on device');
        return;
      } else if (response.errorCode == 'permission') {
        alert('Permission not satisfied');
        return;
      } else if (response.errorCode == 'others') {
        alert(response.errorMessage);
        return;
      }
      console.log('base64 -> ', response.base64);
      console.log('uri -> ', response.uri);
      console.log('width -> ', response.width);
      console.log('height -> ', response.height);
      console.log('fileSize -> ', response.fileSize);
      console.log('type -> ', response.type);
      console.log('fileName -> ', response.fileName);
      setFilePath(response);
    });
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <Text style={styles.titleText}>
        Example of Image Picker in React Native
      </Text>
      <View style={styles.container}>
        {/* <Image
          source={{
            uri: 'data:image/jpeg;base64,' + filePath.data,
          }}
          style={styles.imageStyle}
        /> */}
        <Image
          source={{uri: filePath.uri}}
          style={styles.imageStyle}
        />
        <Text style={styles.textStyle}>{filePath.uri}</Text>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={() => captureImage('photo')}>
          <Text style={styles.textStyle}>
            Launch Camera for Image
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={() => captureImage('video')}>
          <Text style={styles.textStyle}>
            Launch Camera for Video
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={() => chooseFile('photo')}>
          <Text style={styles.textStyle}>Choose Image</Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={() => chooseFile('video')}>
          <Text style={styles.textStyle}>Choose Video</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  titleText: {
    fontSize: 22,
    fontWeight: 'bold',
    textAlign: 'center',
    paddingVertical: 20,
  },
  textStyle: {
    padding: 10,
    color: 'black',
    textAlign: 'center',
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 5,
    marginVertical: 10,
    width: 250,
  },
  imageStyle: {
    width: 200,
    height: 200,
    margin: 5,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Known Issue

In case you face any min version issue in Android then you can update minSdkVersion to 21 in yourProject/android/build.gradle

ext {
    buildToolsVersion = "29.0.2"
    minSdkVersion = 21
    compileSdkVersion = 29
    targetSdkVersion = 29
}

Output Screenshots

Android

image_picker_example1.jpg   image_picker_example2.jpg   image_picker_example3.jpg   image_picker_example4.jpg  image_picker_example5.jpg  image_picker_example6.jpg   image_picker_example7.jpg   image_picker_example8.jpg   image_picker_example9.jpg  image_picker_example10.jpg  image_picker_example11.jpg

IOS

image_picker_example12.jpg     image_picker_example13.jpg     image_picker_example14.jpg     image_picker_example15.jpg  image_picker_example16.jpg  image_picker_example17.jpg

This is how you can Pick an Image from the React Native Application. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

16 thoughts on “Example of Image Picker in React Native”

  1. Thank you so much. I was stuck in this Image Picker API integration but your V3.+ version example help me a lot.
    Thanks Again 🙂

    Reply
  2. Hi im using react native image picking and I had tried your approach, it does open the library as expected bit for some reason is not selecting the images, however it does select videos, I cannot figure out the issue here, could you help me please?….

    Reply
  3. I try the same code. But it is showing unhandled promise rejection. TypeError: null is not an object (evaluating ‘_reactNative.NativeModules.ImagePickerManager.launchCamera’)

    Reply
      • Same problem, here’s my log:

        LOG Response = {“assets”: [{“fileName”: “rn_image_picker_lib_temp_5f6cbdf2-c2a7-4cb6-b570-b8d423f613ba.jpg”, “fileSize”: 71256, “height”: 400, “type”: “image/jpeg”, “uri”: “file:///data/user/0/com.abitarefacile/cache/rn_image_picker_lib_temp_5f6cbdf2-c2a7-4cb6-b570-b8d423f613ba.jpg”, “width”: 300}]}
        LOG base64 -> undefined
        LOG uri -> undefined
        LOG width -> undefined
        LOG height -> undefined
        LOG fileSize -> undefined
        LOG type -> undefined
        LOG fileName -> undefined

        Reply
      • Same issue , here is my logs:

        LOG Response = {“assets”: [{“fileName”: “rn_image_picker_lib_temp_5f6cbdf2-c2a7-4cb6-b570-b8d423f613ba.jpg”, “fileSize”: 71256, “height”: 400, “type”: “image/jpeg”, “uri”: “file:///data/user/0/com.abitarefacile/cache/rn_image_picker_lib_temp_5f6cbdf2-c2a7-4cb6-b570-b8d423f613ba.jpg”, “width”: 300}]}
        LOG base64 -> undefined
        LOG uri -> undefined
        LOG width -> undefined
        LOG height -> undefined
        LOG fileSize -> undefined
        LOG type -> undefined
        LOG fileName -> undefined

        Reply
  4. I have the same issue. Here is my log:

    LOG Response = {“assets”: [{“fileName”: “rn_image_picker_lib_temp_e03c0b4c-32b9-4a5d-88dd-e95cacbb2a36.jpg”, “fileSize”: 54550, “height”: 400, “type”: “image/jpeg”, “uri”: “file:///data/user/0/com.awesome/cache/rn_image_picker_lib_temp_e03c0b4c-32b9-4a5d-88dd-e95cacbb2a36.jpg”, “width”: 300}]}
    LOG base64 -> undefined
    LOG uri -> undefined
    LOG width -> undefined
    LOG height -> undefined
    LOG fileSize -> undefined
    LOG type -> undefined
    LOG fileName -> undefined

    Reply
  5. hi ,in my redmi mobile, when i open camera it is working fine, i can able to take the photo, but after clicking photo and clicking on right arrow button the confirm image then the complete app is reloading, please tell me what is the issue in this.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.