This site runs best with JavaScript enabled.
Share

How to build an image picker in React Native

Youssouf El Azizi

August 07, 2021


Originally published on Logrocket Blog

In my experience working with React Native, one of the tasks I've found myself doing most often is building the functionality for uploading images from user devices. This can be challenging if you've never done it before.

In this tutorial, we'll demonstrate how to use React Native Image Crop Picker to enable your users to select images from their devices or use the device's camera to capture and upload live photos to your app.

To show how react-native-image-crop-picker works, we'll create a reusable image picker component that handles permission to select an image from the media library or take a new image using the camera.

By the end of the tutorial, you should use the image picker component like so:

1import * as React from "react";
2import { View } from "react-native";
3import { ImageOrVideo } from "react-native-image-crop-picker";
4import { Avatar } from "./Avatar";
5
6export const Profile = () => {
7 const onAvatarChange = (image: ImageOrVideo) => {
8 console.log(image);
9 // upload image to server here
10 };
11 return (
12 <Avatar
13 onChange={onAvatarChange}
14 source={require("./avatar-placeholder.png")}
15 />
16 );
17};

Here's a simple demo of the finished result:

final-demo

Choosing the right React Native image picker

There are two popular libraries you can use to implement the image picker component: [react-native-image-picker](https://github.com/react-native-image-picker/react-native-image-picker) and react-native-image-crop-picker. React Native Image Picker is another React Native module for selecting media from the device library or camera. So why use React Native Image Crop Picker?

The advantage to using react-native-image-crop-picker is that, unlike react-native-image-picker, it enables you to crop and compress images. This is especially critical when building iOS apps because uploading large files could introduce performance issues. Compressing and cropping images is also helpful for users with low internet speed.

Installing react-native-image-crop-picker

Let's create a new React Native project using a TypeScript template:

1npx react-native init ImagePickerDemo --template react-native-template-typescript

Next, install react-native-image-crop-picker:

1yarn add react-native-image-crop-picker

Because react-native-image-crop-picker comes with some native dependencies, we need to install pod and rebuild the app:

1cd ios && pod install && cd ..

To use react-native-image-crop-picker , you should add the following config to info.plist:

1<key>NSPhotoLibraryUsageDescription</key>
2<string>$(PRODUCT_NAME) would like to upload photos from your photo gallery</string>
3<key>NSCameraUsageDescription</key>
4<string>$(PRODUCT_NAME) requires to access camera for uploading photos to your profile or posts</string>
5<key>NSMicrophoneUsageDescription</key>
6<string>$(PRODUCT_NAME) requires to access Audio recording to record and uplod videos</string>

The NSPhotoLibraryUsageDescription config describes why you need access to user photos and why you're accessing the camera. If you only want to access images from the device library, you don't need to add the NSMicrophoneUsageDescription or NSCameraUsageDescription keys.

Now we're ready to build and open the app:

1yarn ios

Android configuration

The Android configuraiton for react-native-image-crop-picker is as follows.

First, add useSupportLibrary (android/app/build.gradle):

1android {
2 ...
3
4 defaultConfig {
5 ...
6 vectorDrawables.useSupportLibrary = true
7 ...
8 }
9 ...
10}

If you want to use the camera picker in your project, add the following to app/src/main/AndroidManifest.xml:

  • <uses-permission android:name="android.permission.CAMERA"/>
  1. If you want to allow the user to use their front camera, you should also add the following to app/src/main/ AndroidManifest.xml:
  • <uses-feature android:name="android.hardware.camera" android:required="false" />
  • <uses-feature android:name="android.hardware.camera.front" android:required="false" />

It's important to mention that you need to upgrade to Android SDK 26+. If you're using React Native 0.64, you're safe. If that's not the case, make sure to updateandroid/app/build.gradle:

1android {
2 compileSdkVersion 27
3 buildToolsVersion "27.0.3"
4 ...
5
6 defaultConfig {
7 ...
8 targetSdkVersion 27
9 ...
10 }
11 ...
12}

Building an avatar profile update

In this section, we'll build a simple screen to update the user avatar. The idea is to create an image picker component to allow the user to upload a new avatar. The avatar component should extend its prop from the Image component, and we'll add onChange to handle uploading a new image from the user device.

We'll wrap our image with a pressable component to open the photo library when the user presses their profile picture. Opening the image library is as easy as calling the openPicker function from react-native-image-crop-picker.

Let's add a crop feature that allows users to crop the selected image before uploading:

1import React from "react";
2import { Image, ImageProps, StyleSheet, TouchableOpacity } from "react-native";
3import ImagePicker, { ImageOrVideo } from "react-native-image-crop-picker";
4
5interface AvatarProps extends ImageProps {
6 onChange?: (image: ImageOrVideo) => void;
7}
8
9export const Avatar = (props: AvatarProps) => {
10 const [uri, setUri] = React.useState(props.source?.uri || undefined);
11
12 const pickPicture = () => {
13 ImagePicker.openPicker({
14 width: 300,
15 height: 400,
16 cropping: true,
17 }).then((image) => {
18 setUri(image.path);
19 props.onChange?.(image);
20 });
21 };
22 return (
23 <TouchableOpacity onPress={pickPicture}>
24 <Image
25 style={styles.avatar}
26 {...props}
27 source={uri ? { uri } : props.source}
28 />
29 </TouchableOpacity>
30 );
31};
32
33const styles = StyleSheet.create({
34 avatar: {
35 paddingTop: 20,
36 height: 100,
37 width: 100,
38 borderRadius: 100,
39 padding: 20,
40 },
41});

Now that our avatar component is ready to be used, let's create a profile screen and update the user's profile picture:

1import * as React from "react";
2import { StatusBar, StyleSheet, View } from "react-native";
3import { ImageOrVideo } from "react-native-image-crop-picker";
4import { Avatar } from "./Avatar";
5import { UserInfo } from "./UserInfo";
6
7export const Profile = () => {
8 const onAvatarChange = (image: ImageOrVideo) => {
9 console.log(image);
10 // upload image to server here
11 };
12 return (
13 <View style={styles.scroll}>
14 <StatusBar barStyle="dark-content" />
15 <View style={styles.userRow}>
16 <Avatar
17 onChange={onAvatarChange}
18 source={require("./avatar-placeholder.png")}
19 />
20 <UserInfo />
21 </View>
22 <View style={styles.content} />
23 </View>
24 );
25};
26
27const styles = StyleSheet.create({
28 scroll: {
29 backgroundColor: "white",
30 flex: 1,
31 },
32 userRow: {
33 alignItems: "center",
34 padding: 15,
35 marginTop: 70,
36 },
37 content: {
38 flex: 1,
39 backgroundColor: "#d8d8db",
40 },
41});

Here we added the onChange prop to the avatar. This will provide us with all the file info, which we can easily use to upload it to our server. Here is the result:

demo

Taking a photo using the device camera

Let's say we want to give the user the ability to take a photo from their camera and upload it. We should also give the user the option to select a photo from the library or use their device camera to take a new photo.

Note that openCamera won't work on iOS Simulator. To test it, you should run the app on a real device.

To use the camera, we only need to call the openCamera function instead of openPicker:

1import React from "react";
2import {
3 Image,
4 ImageProps,
5 Pressable,
6 SafeAreaView,
7 StyleSheet,
8 Text,
9 TouchableOpacity,
10} from "react-native";
11import ImagePicker, { ImageOrVideo } from "react-native-image-crop-picker";
12import Modal from "react-native-modal";
13import { CameraIcon, ImageIcon } from "./icons";
14
15interface AvatarProps extends ImageProps {
16 onChange?: (file: ImageOrVideo) => void;
17}
18
19export const Avatar = (props: AvatarProps) => {
20 const [uri, setUri] = React.useState(props.source?.uri || undefined);
21 const [visible, setVisible] = React.useState(false);
22 const close = () => setVisible(false);
23 const open = () => setVisible(true);
24 const chooseImage = () => {
25 ImagePicker.openPicker({
26 width: 300,
27 height: 400,
28 cropping: true,
29 })
30 .then((image) => {
31 setUri(image.path);
32 props.onChange?.(image);
33 })
34 .finally(close);
35 };
36
37 const openCamera = () => {
38 ImagePicker.openCamera({
39 width: 300,
40 height: 400,
41 cropping: true,
42 })
43 .then((image) => {
44 setUri(image.path);
45 props.onChange?.(image);
46 })
47 .finally(close);
48 };
49
50 return (
51 <>
52 <TouchableOpacity onPress={chooseImage}>
53 <Image
54 style={styles.avatar}
55 {...props}
56 source={uri ? { uri } : props.source}
57 />
58 </TouchableOpacity>
59 <Modal
60 isVisible={visible}
61 onBackButtonPress={close}
62 onBackdropPress={close}
63 style={{ justifyContent: "flex-end", margin: 0 }}
64 >
65 <SafeAreaView style={styles.options}>
66 <Pressable style={styles.option} onPress={chooseImage}>
67 <ImageIcon />
68 <Text>Library </Text>
69 </Pressable>
70 <Pressable style={styles.option} onPress={openCamera}>
71 <CameraIcon />
72 <Text>Camera</Text>
73 </Pressable>
74 </SafeAreaView>
75 </Modal>
76 </>
77 );
78};
79
80const styles = StyleSheet.create({
81 avatar: {
82 paddingTop: 20,
83 height: 100,
84 width: 100,
85 borderRadius: 100,
86 padding: 20,
87 },
88
89 options: {
90 backgroundColor: "white",
91 flexDirection: "row",
92 borderTopRightRadius: 30,
93 borderTopLeftRadius: 30,
94 },
95 option: {
96 flex: 1,
97 justifyContent: "center",
98 alignItems: "center",
99 },
100});

Here's a demo of our finished React Native app:

final-demo

Conclusion

Now you can copy-paste this image picker component whenever you need to build an image upload feature in a React Native app.

The full code is available in this Github repo if you want to play around with this project. I hope you found that interesting, informative, and entertaining. I would be more than happy to hear your remarks and thoughts.

If you think other people should read this post. Tweet, share and Follow me on twitter for the next articles.

Share article 👉

Hire Me !

👋 Hey, if you search for a reputable react-native developer with more than four years of building mobile applications to produce top-quality Applications, you are in the right place; Get in touch to discuss your needs now!

How i can help you?

  • Building your next mobile application using react native best practices with performance in mind
  • Provide consulting and code review for your team to help them build clean and mobile preferment application
  • Investigate on application's performance and issues and help you fix them and optimize application performance.


Get updates via email

JavaScript, React, React Native and web thoughts


Youssouf El Azizi © 2021