Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NextJS
  • Material UI
  • React Bootstrap
  • React Suite
  • Ant Design
  • Reactstrap
  • BlueprintJS
  • React Desktop
  • React Native
  • React Rebass
  • React Spring
  • React Evergreen
  • ReactJS
  • ReactJS
  • JS Formatter
  • Web Technology
Open In App
Next Article:
Create File Explorer App using React-Native
Next article icon

Create an Image/Video Gallery using React-Native

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An Image/Video Gallery is a common feature in mobile applications. This article will guide you for creating an Image/Video Gallery using React Native.We will learn to build an Image/Video Gallery app using React-Native. In this app, we will display the images and videos in the form of a grid, and on clicking, we can view them. If an image is clicked, the image viewer is opened, similarly, if a video is clicked, a video player is launched. By the end of this tutorial, you will have solid understanding of MediaLibrary usage in React Native.

Preview of final output: Let us have a look at how the final output will look like

preview image of image/video gallery app

Prerequisites and Technolgies Used

  • Introduction to React Native
  • Introduction React Native Components
  • React Native State
  • React Native Props
  • Expo CLI
  • Node JS and npm (Node Package Manager)

Approach to create Image/Video Gallery App

  • The application will be single page app.
  • It will contain two types, image and video so we used useState hook with default value of image.
  • Using the FlatList component, we load the assets from MediaLibrary. It gets the permission from user in the device.
  • On getting the assets, we display the image and videos in different tabs using Buttons.
  • We wrap the images with Pressable. On clicking, we set the file location .
  • The Modal component becomes visible on setting the imageName variable. Here we check if image, we display an image, else video.

Steps to create the project:

Step 1: Create the project:

npx create-expo-app image-video-gallery-app


Step 2: Navigate to the project

cd image-video-gallery-app


Step 3: Install the required libraries

npx expo install expo-av
npx expo install expo-image
npx expo install expo-media-library


Step 4: Configuration in app.json/app.config.js

{
"expo": {
"plugins": [
[
"expo-media-library",
{
"photosPermission": "Allow $(name) to access your photos.",
"savePhotosPermission": "Allow $(name) to save photos.",
"videosPermission": "Allow $(name) to access your videos.",
"isAccessMediaLocationEnabled": true
}
]
]
}
}


Project Structure:

Screenshot-2023-12-03-081717

The updated dependencies in package.json file will look like:

"dependencies": {
"expo": "~49.0.15",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.6",
"expo-media-library": "~15.4.1",
"expo-image": "~1.3.5",
"expo-av": "~13.4.1"
},
"devDependencies": {
"@babel/core": "^7.20.0"
}

Example: In this example we are following the above-explained approach.

JavaScript
// App.js  import { StatusBar } from "expo-status-bar"; import { 	Button, 	FlatList, 	Modal, 	Pressable, 	ScrollView, 	StyleSheet, 	Text, 	View, } from "react-native"; import * as MediaLibrary from "expo-media-library"; import { useState } from "react"; import { Image } from "expo-image"; import { Video, ResizeMode } from "expo-av"; export default function App() { 	const [galleryFiles, setGalleryFiles] = useState([]); 	const [currentImage, setCurrentImage] = useState(""); 	const [mediaType, setMediaType] = useState("image"); 	const fetchMedia = async (first, mediaType) => { 		const { status } = await MediaLibrary.requestPermissionsAsync(); 		if (status === "granted") { 			const media = await MediaLibrary.getAssetsAsync({ 				first: first + 30, 				sortBy: MediaLibrary.SortBy.creationTime, 				mediaType: 					mediaType === "image" 						? MediaLibrary.MediaType.photo 						: MediaLibrary.MediaType.video, 			}); 			setGalleryFiles(media.assets); 		} 	}; 	const renderItem = ({ item }) => ( 		<View style={styles.imageContainer}> 			<Pressable 				onPress={() => { 					setCurrentImage(item.uri); 					setMediaType(item.mediaType); 				}} 			> 				<Image 					source={{ uri: item.uri }} 					style={{ width: 200, height: 200 }} 				/> 			</Pressable> 		</View> 	);  	return ( 		<View style={styles.container}> 			<StatusBar style="auto" /> 			<Text style={styles.heading}>Welcome to GeeksforGeeks</Text>  			<View 				style={{ 					flexDirection: "row", 					justifyContent: "space-around", 					width: "100%", 					padding: 10, 				}} 			> 				<Button 					title="Images" 					onPress={() => { 						setMediaType("image"); 						fetchMedia(0, "image"); 					}} 				/> 				<Button 					title="Videos" 					onPress={() => { 						setMediaType("video"); 						fetchMedia(0, "video"); 					}} 				/> 			</View>  			{/* view full image in modal */} 			<Modal visible={currentImage !== ""} transparent={false}> 				<View style={{ flex: 1, backgroundColor: 0 }}> 					<Pressable 						style={{ 							position: "absolute", 							top: 40, 							zIndex: 1, 							flex: 1, 							alignSelf: "center", 						}} 						title="Close" 						onPress={() => setCurrentImage("")} 					> 						<Text 							style={{ 								color: "black", 								fontSize: 20, 								padding: 10, 								backgroundColor: "white", 							}} 						> 							Close 						</Text> 					</Pressable> 					{mediaType === "video" ? ( 						<Video 							style={{ 								width: "100%", 								height: "100%", 							}} 							source={{ 								uri: currentImage, 							}} 							useNativeControls 							resizeMode={ResizeMode.CONTAIN} 							isLooping 						/> 					) : ( 						<Image 							source={{ uri: currentImage }} 							style={{ width: "100%", height: "100%" }} 						/> 					)} 				</View> 			</Modal> 			<View style={styles.scrollContainer}> 				<Text style={{ fontSize: 20, marginBottom: 20 }}> 					My Gallery 				</Text> 				<FlatList 					data={galleryFiles} 					renderItem={renderItem} 					keyExtractor={(item) => item.id} 					numColumns={3} 					onEndReached={() => { 						fetchMedia(galleryFiles.length, mediaType); 					}} 					onLayout={() => { 						fetchMedia(galleryFiles.length, mediaType); 					}} 				/> 			</View> 		</View> 	); }  const styles = StyleSheet.create({ 	container: { 		flex: 1, 		justifyContent: "center", 		alignItems: "center", 		marginTop: "10%", 	}, 	scrollContainer: { 		flex: 1, 		marginTop: 20, 		width: "100%", 	}, 	heading: { 		color: "green", 		fontSize: 30, 		textAlign: "center", 		fontWeight: "bold", 	}, 	imageContainer: { 		flex: 1, 		margin: 1, 		aspectRatio: 1, // This ensures that images maintain their aspect ratio 		borderRadius: 8, 		overflow: "hidden", 	}, 	image: {}, }); 

Steps to run the application:

Step 1: Navigate to the terminal or command prompt and type the required command there to run the React native application.

npx expo start


Step 2: Depending on your operating system, type the following command in terminal

  • To run on Android:
npx react-native run-android


  • To run on Ios:
npx react-native run-ios


Step optional: To run on Web, you need to install the following packages

npx expo install react-dom react-native-web @expo/webpack-config


Step 3: To run on web, press w on Terminal will application is running. For Android/IOS, install the Expo app and scan the QR code or enter the link of Metro in the Terminal.

Output:


Next Article
Create File Explorer App using React-Native

M

manavsarkar07
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • React-Native
  • Geeks Premier League 2023

Similar Reads

  • Create an Image/Video Downloader App using React-Native
    There are a vast amount of videos available on the internet but we are not able to download most of them. In this article, you will be guided through the step-by-step to create an Image/Video Downloader App using React-Native. Preview of final output: Let us have a look at how the final output will
    3 min read
  • Create an Image Crop Tool using React-Native
    In this tutorial, we are going to build an Image crop tool using React-Native. The Image Crop tool is a very important tool for cropping the Images. It will allow the users to pick an image from storage, crop it, and later save it locally. Preview Image:Prerequisites Introduction to React NativeReac
    4 min read
  • Create an Image Carousal using React-Native
    In this article, we will build the Image Carousal using React Native language. In this interactive application, we have taken some sample GFG course images which are automatically and manually scrolled. When the user clicks on the image, the additional information about that course is shown in a mod
    5 min read
  • Create File Explorer App using React-Native
    Creating a File Explorer app using React Native provides a seamless way to explore and interact with the device's file system on both iOS and Android platforms. In this tutorial, we'll guide you through the process of building a simple yet functional File Explorer app. Output Preview: Prerequisites:
    3 min read
  • Create an Employee Management using React-Native
    Creating the Employee Management Application using React-Native is skill developing project. In this project, the application admin can manage the employees by adding them dynamically, updating the details, and deleting the employee as per the requirement. In this article, we will develop this Emplo
    6 min read
  • Create a 2048 Game using React-Native
    In this article, we are going to implement a 2048 Game using React Native. The 2048 game is a popular sliding puzzle game that involves combining tiles with the same number to reach the tile with the number 2048. Players can move the tiles in four directions: up, down, left, or right. PrerequisiteRe
    7 min read
  • Create an Image Resize and Editor using React-Native
    Image manipulation in mobile apps is an important functionality, from cropping and resizing to adding filters or overlays. In this tutorial, you will learn the process of building a simple Image Resize and Editor application using React-Native. This project aims to provide a foundation to integrate
    3 min read
  • Create a Video Editor using React
    Video Editor is one of the useful apps in day-to-day life. In this article, we’ll walk you through the process of building a basic video editing app using React Native. The application enables users to upload, trim, and convert specific scenes to GIFs and then download the final edited file directly
    6 min read
  • Create a Memory Pair Game using React-Native
    In this article, we will build the interactive Memory Pair Game using the React Native language. We are displaying the 12 boxes to the user, in the user has to click on each box, and when the user clicks on the box the random icon will be shown. Users have to guess or find its match by clicking on t
    5 min read
  • Create Memes Generator App using React-Native
    The Me­me Generator App is a mobile­ application that allows users to effortlessly create memes. With its use­r-friendly interface, use­rs can choose from a wide collection of popular me­me templates and add their own customized text to the top and bottom. In this article, we will see how we can bui
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences