Photo and Video Access in React Native Apps - React Native Expert
banner shap banner shap

How to Implement Photo and Video Access in React Native Apps

Add photo and video access to your React Native app easily.

Nov 19, 2024

Save for later

Implement Photo and Video Access in React Native

Introduction

When building a React Native app that requires users to access photos or videos from their device’s gallery, integrating the @react-native-camera-roll/camera-roll library is a great solution. This library provides an easy way to access and manage the media on the user’s device. In this article, we’ll walk through the steps to implement photo and video access using this library and how to utilize it for a smooth and user-friendly experience.

What is @react-native-camera-roll/camera-roll?

@react-native-camera-roll/camera-roll is a React Native library that allows you to access the camera roll (i.e., the photo and video gallery) on iOS and Android devices. It provides an API to get a list of media items from the device, like photos and videos, which can then be displayed in your app.

Why Use @react-native-camera-roll/camera-roll?

  1. Access to Gallery: This library allows your app to access the media in the user’s gallery on both iOS and Android.
  2. Easy Integration: It provides an easy-to-use API to retrieve photos, videos, and media details, making it simple to integrate into your React Native app.
  3. Cross-Platform Compatibility: As a cross-platform solution, it ensures that your app behaves the same way across both iOS and Android.

How to Set Up @react-native-camera-roll/camera-roll

1. Install the Library
First, you need to install the @react-native-camera-roll/camera-roll package in your React Native project.
				
					npm install @react-native-camera-roll/camera-roll
				
			

After installing, make sure to link the package. In most cases, this should be automatic with React Native 0.60+ (due to auto-linking).

2. Add Permissions

To access photos and videos from the device, you need to request permission from the user. Add the necessary permissions for iOS and Android.

For iOS, open the Info.plist file and add the following keys:

				
					<key>NSPhotoLibraryUsageDescription</key>
<string>Your app needs access to photos</string>

				
			

For Android, open the AndroidManifest.xml file and add:

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

				
			
3. Get Photos or Videos from the Gallery

Once the library is installed and the necessary permissions are set, you can use it to retrieve media from the gallery. Here’s an example of how to fetch photos from the gallery:

				
					import React, { useEffect, useState } from 'react';
import { View, FlatList, Text, Image } from 'react-native';
import CameraRoll from '@react-native-camera-roll/camera-roll';

const GalleryScreen = () => {
  const [photos, setPhotos] = useState([]);

  useEffect(() => {
    // Fetch the media from the device
    CameraRoll.getPhotos({
      first: 20, // Number of photos to fetch
      assetType: 'Photos', // Only get photos
    })
    .then(r => setPhotos(r.edges)) // Store the fetched photos in the state
    .catch((err) => console.log('Error fetching photos: ', err));
  }, []);


  return (
    <View style={{ flex: 1, paddingTop: 50 }}>
      <FlatList
        data={photos}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <View style={{ marginBottom: 10 }}>
            <Image
              source={{ uri: item.node.image.uri }}
              style={{ width: 100, height: 100 }}
            />
          </View>
        )}
      />
    </View>
  );
};

export default GalleryScreen;

				
			

In this example, the app fetches the first 20 photos from the user’s gallery and displays them in a FlatList.

4. Handle Videos

If you want to access videos, you can modify the assetType to ‘Videos’:

				
					CameraRoll.getPhotos({
  first: 20, // Number of videos to fetch
  assetType: 'Videos', // Get videos
})
.then(r => setVideos(r.edges)) // Store videos in the state
.catch((err) => console.log('Error fetching videos: ', err));

				
			

You can also fetch both photos and videos by using assetType: ‘All’.

5. Displaying Images and Videos

You can display both images and videos from the gallery in your app. For videos, you might use a video player like react-native-video. Here’s how you can display videos:

				
					import Video from 'react-native-video';

const renderItem = ({ item }) => {
  if (item.node.type === 'video') {
    return (
      <Video
        source={{ uri: item.node.image.uri }}
        style={{ width: '100%', height: 200 }}
        controls={true}
      />
    );
  } else {
    return (
      <Image
        source={{ uri: item.node.image.uri }}
        style={{ width: 100, height: 100 }}
      />
    );
  }
};

				
			

This code checks if the item is a video and uses a video player to display it, while photos are displayed as images.

6. Handling Permissions

For Android, starting from Android 6.0 (API 23), you need to request runtime permissions for reading and writing to the storage. You can handle these permissions using the react-native-permissions library.

Here’s an example of how to request permissions at runtime:

				
					npm install react-native-permissions

				
			

Then, use the following code:

				
					import { PermissionsAndroid } from 'react-native';
const requestPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      {
        title: "Photo Library Permission",
        message: "App needs access to your photo library",
      }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can access the gallery");
    } else {
      console.log("Gallery permission denied");
    }
  } catch (err) {
    console.warn(err);
  }
};

				
			

Conclusion

By using @react-native-camera-roll/camera-roll, you can easily access and display photos and videos from the user’s device in your React Native app. With simple installation, permission handling, and usage of its API, you can build powerful media-related features in your app. If you’re a React Native App Development Company or a React Native specialist looking to integrate media access features in your app, Hire React Native developer or using React Native consulting services can help streamline the process. With the help of experts, you can make sure that your app provides a smooth and user-friendly media experience, just like the top apps available today.
5/5 - (2 votes)