React Native course · Module 13: Native APIs

expo-media-library - Photo gallery

1 min read ·
In this lesson5

Access the user's photos and videos!

Installation

npx expo install expo-media-library

Fetching media

import * as MediaLibrary from 'expo-media-library';

async function getPhotos() {
  const { status } = await MediaLibrary.requestPermissionsAsync();

  if (status !== 'granted') {
    Alert.alert('No gallery permissions');
    return [];
  }

  const { assets } = await MediaLibrary.getAssetsAsync({
    mediaType: MediaLibrary.MediaType.photo,
    first: 20, // Limit
    sortBy: MediaLibrary.SortBy.creationTime,
  });

  return assets;
}

Fetching albums

async function getAlbums() {
  const albums = await MediaLibrary.getAlbumsAsync();
  return albums;
}

async function getAlbumPhotos(albumId: string) {
  const { assets } = await MediaLibrary.getAssetsAsync({
    album: albumId,
    mediaType: MediaLibrary.MediaType.photo,
  });
  return assets;
}
async function saveToGallery(uri: string) {
  const { status } = await MediaLibrary.requestPermissionsAsync();

  if (status !== 'granted') {
    throw new Error('No permissions');
  }

  // Save photo
  const asset = await MediaLibrary.createAssetAsync(uri);

  // Optionally: add to album
  const album = await MediaLibrary.getAlbumAsync('Atlantis');
  if (album) {
    await MediaLibrary.addAssetsToAlbumAsync([asset], album, false);
  } else {
    await MediaLibrary.createAlbumAsync('Atlantis', asset, false);
  }

  return asset;
}

Deleting media

async function deleteAsset(assetId: string) {
  await MediaLibrary.deleteAssetsAsync([assetId]);
}
Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';
import { View, Text, Image, FlatList, StyleSheet } from 'react-native';
import * as MediaLibrary from 'expo-media-library';

// Hook for handling the user's photo gallery
function useGallery() {
  const [photos, setPhotos] = useState<MediaLibrary.Asset[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      // TODO: request gallery permissions:
      //   const { status } = await MediaLibrary.requestPermissionsAsync();
      //   if (status !== 'granted') { setLoading(false); return; }

      // TODO: fetch the first 20 photos:
      //   const { assets } = await MediaLibrary.getAssetsAsync({
      //     mediaType: MediaLibrary.MediaType.photo,
      //     first: 20,
      //     sortBy: MediaLibrary.SortBy.creationTime,
      //   });
      //   setPhotos(assets);

      setLoading(false);
    })();
  }, []);

  return { photos, loading };
}

export default function App() {
  const { photos, loading } = useGallery();

  if (loading) {
    return (
      <View style={styles.screen}>
        <Text style={styles.title}>Loading gallery...</Text>
      </View>
    );
  }

  return (
    <View style={styles.screen}>
      <Text style={styles.title}>Atlantis Gallery</Text>
      <FlatList
        data={photos}
        numColumns={3}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <Image source={{ uri: item.uri }} style={styles.thumb} />
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    padding: 24,
    backgroundColor: '#1a5276',
  },
  title: {
    fontSize: 22,
    color: '#fff',
    fontWeight: '600',
    marginBottom: 16,
  },
  thumb: {
    width: 100,
    height: 100,
    margin: 2,
    borderRadius: 8,
  },
});

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you install expo-media-library?

  2. 2. How do you fetch photos from the gallery?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange saving to the gallery:

  • Code editor

    Complete the useGallery code.

  1. QuestionInstalling media-library
  2. QuestiongetAssetsAsync
  3. QuestionMediaType
  4. Put in ordercreateAssetAsync
  5. QuestiongetAlbumsAsync
  6. Coding taskGallery hook

Useful articles