How to Show Photos of your Device as a Gallery in React Native

Last Updated on December 15, 2020.

Apps such as image editing apps or social apps allow users to use their own photos. In this react native tutorial, I am going to show you a camera roll example where the images of your device are listed as a grid.

CameraRoll is a react native API that gives access to the user’s photos and videos. First of all, let’s see how to set up a CameraRoll in your react native project.

Install CameraRoll using the following command.

npm install @react-native-community/cameraroll --save

Now you should have permission to access photos in both iOS and Android devices. In Android, add the following permission in AndroidManifest.xml file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

In the case of iOS, add two keys namely NSPhotoLibraryUsageDescription and NSPhotoLibraryAddUsageDescription in Info.plist file with strings as values that define how you are going to use the data.

You have to invoke CameraRoll.getPhotos() method to retrieve photos of the device. It returns a promise where you get all data related to the photos and videos.

CameraRoll.getPhotos({
        first: 50,
        assetType: 'Photos',
      })
      .then(res => {
        this.setState({ data: res.edges });
      })
      .catch((error) => {
         console.log(error);
      });

Following is the complete react native camera roll example where the latest fifty photos of the user’s device are shown as a grid using FlatList.

Class Component

import React, { Component } from 'react';
import { View, Image, FlatList, PermissionsAndroid, Platform } from 'react-native';
import CameraRoll from "@react-native-community/cameraroll";

export default class camera extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data:''
    };
  }

  async componentDidMount(){
    if (Platform.OS === 'android') {
        const result = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
            title: 'Permission Explanation',
            message: 'ReactNativeForYou would like to access your photos!',
          },
        );
        if (result !== 'granted') {
          console.log('Access to pictures was denied');
          return;
        }
      }

      CameraRoll.getPhotos({
        first: 50,
        assetType: 'Photos',
      })
      .then(res => {
        this.setState({ data: res.edges });
      })
      .catch((error) => {
         console.log(error);
      });
    
  }

  render() {
    return (
      <View>
        <FlatList
        data={this.state.data}
        numColumns={3}
        renderItem={({ item }) => <Image
           style={{
             width: '33%',
             height: 150,
           }}
           source={{ uri: item.node.image.uri }}
         />}
      />
      </View>
    );
  }
}

Function Component

import React, {useEffect, useState} from 'react';
import {
  View,
  Image,
  FlatList,
  PermissionsAndroid,
  Platform,
} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';

const Camera = () => {
  const [data, setData] = useState('');
  const getPhotos = () => {
    CameraRoll.getPhotos({
      first: 50,
      assetType: 'Photos',
    })
      .then((res) => {
        setData(res.edges);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const askPermission = async () => {
    if (Platform.OS === 'android') {
      const result = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: 'Permission Explanation',
          message: 'ReactNativeForYou would like to access your photos!',
        },
      );
      if (result !== 'granted') {
        console.log('Access to pictures was denied');
        return;
      } else {
        getPhotos();
      }
    } else {
      getPhotos();
    }
  };

  useEffect(() => {
    askPermission();
  }, []);

  return (
    <View>
      <FlatList
        data={data}
        numColumns={3}
        renderItem={({item}) => (
          <Image
            style={{
              width: '33%',
              height: 150,
            }}
            source={{uri: item.node.image.uri}}
          />
        )}
      />
    </View>
  );
};

export default Camera;

Following is the output of this react native tutorial.

I hope you find this react native tutorial helpful. Thank you for reading.

4 thoughts on “How to Show Photos of your Device as a Gallery in React Native”

  1. Isabelle Kreienbink

    Is there any way to use this to click on one of the videos and watch them in the app?

  2. Hi, nice tutorial and straight to point. Can I use the same method to get video? I want to create video gallery instead, please I need help with it. Thanks.

Leave a Reply

%d bloggers like this: