0
0
React Nativemobile~5 mins

Image picker in React Native

Choose your learning style9 modes available
Introduction

We use an image picker to let users choose pictures from their phone or take new photos. This makes apps more fun and personal.

When users want to upload a profile picture in a social app.
When users need to attach photos to a message or post.
When users want to scan documents or take pictures inside the app.
When users want to customize content with their own images.
Syntax
React Native
import {launchImageLibrary} from 'react-native-image-picker';

const pickImage = () => {
  launchImageLibrary({mediaType: 'photo'}, (response) => {
    if (!response.didCancel && !response.errorCode) {
      console.log(response.assets[0].uri);
    }
  });
};

Use launchImageLibrary to open the phone's gallery.

Check response.didCancel to see if the user canceled picking.

Examples
Open gallery to pick photos only.
React Native
launchImageLibrary({mediaType: 'photo'}, callback);
Open gallery to pick videos only.
React Native
launchImageLibrary({mediaType: 'video'}, callback);
Allow picking photos or videos.
React Native
launchImageLibrary({mediaType: 'mixed'}, callback);
Sample App

This app shows a button to pick an image from the gallery. When the user picks one, it displays the image below the button.

React Native
import React, {useState} from 'react';
import {View, Button, Image, StyleSheet} from 'react-native';
import {launchImageLibrary} from 'react-native-image-picker';

export default function App() {
  const [photoUri, setPhotoUri] = useState(null);

  const pickImage = () => {
    launchImageLibrary({mediaType: 'photo'}, (response) => {
      if (!response.didCancel && !response.errorCode && response.assets && response.assets.length > 0) {
        setPhotoUri(response.assets[0].uri);
      }
    });
  };

  return (
    <View style={styles.container}>
      <Button title="Pick an Image" onPress={pickImage} />
      {photoUri && <Image source={{uri: photoUri}} style={styles.image} />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  image: {
    width: 200,
    height: 200,
    marginTop: 20,
    borderRadius: 10
  }
});
OutputSuccess
Important Notes

Remember to add permissions in your app config for accessing photos.

Test on a real device because simulators may not have a photo gallery.

Handle user canceling the picker gracefully to avoid errors.

Summary

Image picker lets users select or take photos inside your app.

Use launchImageLibrary with options to control media type.

Always check if the user canceled or if there was an error.