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 an Image to Text App using React-Native
Next article icon

Create an Image Carousal using React-Native

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

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 modal with the course name and description. We have styled the appearance using basic styling properties.

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

image_123986672

Prerequisites

  • React Native
  • NPM (Node Package Manager)

Approach to Creating Image Carousel

The code snippet below is built in React Native which is the basic and simple implementation of Image Coarousal. In this application, we have used the useState hook to manage the state of the application. useEffect is used to manage the automatic scrolling and useRef to update the DOM. Here, we have taken the Image component where we are rendering the sample GFG course images through their URLs. Then, we create the Carousal effects and simultaneously build the Modal component which will show the information of course when the image is been clicked.

Steps to install & configure React Native:

Step 1: Create a react native application by using this command:

npx create-expo-app image-carousal

Step 2: After creating your project folder, i.e. image-carousal, use the following command to navigate to it:

cd  image-carousal

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"
}

Project Structure:

PS

Example: Implementation of the above approach using React JS. Functionalities contain files as follows:

  • App.js: It is a parent component that calls the Image component in it.
  • Image.js: This is the component that is responsible for rendering the images and also provides the functionality of carousal with modal.
JavaScript
// App.js import React from 'react'; import { StyleSheet, View, Text } from 'react-native'; import ImageCarousel from './Image'; export default function App() {     return (         <View style={styles.container}>             <Text style={styles.title}>                 GeeksforGeeks             </Text>             <Text style={styles.subtitle}>                 Image Carousel in React-Native             </Text>             <ImageCarousel />         </View>     ); } const styles = StyleSheet.create({     container: {         flex: 1,         justifyContent: 'center',         alignItems: 'center',         backgroundColor: '#f5fcff',     },     title: {         fontSize: 24,         fontWeight: 'bold',         color: 'green',         marginBottom: 10,     },     subtitle: {         fontSize: 18,         color: '#333',         marginBottom: 20,     }, }); 
JavaScript
// Image.js import React, { useState, useEffect, useRef } from 'react'; import {     View,     Text,     Image,     StyleSheet,     ScrollView,     Dimensions,     TouchableOpacity,     Animated,     Modal, } from 'react-native'; const { width } = Dimensions.get('window'); const height = (width * 14) / 20; const gfgImages = [ 'https://media.geeksforgeeks.org/img-practice/banner/dsa-to-development-coding-guide-thumbnail.png?v=19678', 'https://media.geeksforgeeks.org/img-practice/banner/full-stack-node-thumbnail.png?v=19678', 'https://media.geeksforgeeks.org/img-practice/banner/gate-data-science-and-artificial-intelligence-da-2024-thumbnail.png?v=19678', 'https://media.geeksforgeeks.org/img-practice/banner/data-science-live-thumbnail.png?v=19678', ]; const gfgCourses = [     {         title: 'DSA to Development Coding Guide',         description: 'Learn the essentials of Data Structures and Algorithms for development.',     },     {         title: 'Full Stack Node.js',         description: 'Master the art of Full Stack Development with Node.js.',     },     {         title: 'GATE Data Science and AI',         description: 'Prepare for GATE with a focus on Data Science and Artificial Intelligence.',     },     {         title: 'Data Science Live',         description: 'Explore the world of Data Science through live projects and examples.',     }, ]; const ImageCarousel = () => {     const [activeInd, setActiveInd] = useState(0);     const [modalShow, setModalShow] = useState(false);     const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);     const scrollX = new Animated.Value(0);     const scrollViewRef = useRef();     const imageClickFunction = (ind) => {         setActiveInd(ind);         setModalShow(true);     };     useEffect(() => {         let inter;         if (autoScrollEnabled) {             inter = setInterval(() => {                 const newInd = (activeInd + 1) % gfgImages.length;                 setActiveInd(newInd);                 scrollViewRef.current.scrollTo({ x: newInd * width, animated: true });             }, 4000);         }         return () => clearInterval(inter);     }, [activeInd, autoScrollEnabled]);      return (         <View style={styles.container}>             <ScrollView ref={scrollViewRef}                         horizontal                         pagingEnabled                         showsHorizontalScrollIndicator={false}                         onMomentumScrollEnd={(event) => {                             const newIndex = Math.floor                             (event.nativeEvent.contentOffset.x / width);                             setActiveInd(newIndex);                 }}                 onScroll={Animated.event(                     [{ nativeEvent: { contentOffset: { x: scrollX } } }],                     { useNativeDriver: false }                 )}>                 {gfgImages.map((image, index) => (                     <TouchableOpacity   key={index}                                             activeOpacity={0.9}                                          style={styles.imageContainer}                                             onPress={() => imageClickFunction(index)}>                         <Image source={{ uri: image }} style={styles.image} />                     </TouchableOpacity>                 ))}             </ScrollView>             <View style={styles.pagination}>                 {gfgImages.map((_, index) => (                     <Animated.View key={index}                                    style={[styles.paginationDot,{                                     opacity: scrollX.interpolate({                                     inputRange: [                                         (index - 1) * width,                                         index * width,                                         (index + 1) * width,                                     ],                                     outputRange: [0.5, 1, 0.5],                                     extrapolate: 'clamp',                                 })}]}/>                 ))}             </View>             <Modal animationType="slide"                    transparent={true}                    visible={modalShow}                    onRequestClose={() => setModalShow(false)}>                 <View style={styles.modalContainer}>                     <View style={styles.modalContent}>                         <Text style={styles.modalTitle}>                             {gfgCourses[activeInd].title}                         </Text>                         <Text style={styles.modalDescription}>                             {gfgCourses[activeInd].description}                         </Text>                         <TouchableOpacity style={styles.closeButton}                                           onPress={() => setModalShow(false)}>                             <Text style={styles.closeButtonText}>Close</Text>                         </TouchableOpacity>                     </View>                 </View>             </Modal>         </View>     ); }; const styles = StyleSheet.create({     container: {         width,         height,         backgroundColor: '#272',         borderRadius: 10,         overflow: 'hidden',     },     imageContainer: {         width,         height,         borderRadius: 10,         overflow: 'hidden',     },     image: {         width,         height,         resizeMode: 'cover',         borderRadius: 10,         borderWidth: 4,         borderColor: '#ff0000',     },     pagination: {         flexDirection: 'row',         position: 'absolute',         bottom: 20,         alignSelf: 'center',     },     paginationDot: {         width: 10,         height: 10,         borderRadius: 5,         backgroundColor: '#6b52ae',         margin: 8,     },     modalContainer: {         flex: 1,         justifyContent: 'center',         alignItems: 'center',         backgroundColor: 'rgba(0, 0, 0, 0.5)',     },     modalContent: {         backgroundColor: '#fff',         borderRadius: 10,         padding: 20,         width: width - 40,         alignItems: 'center',     },     modalTitle: {         fontSize: 24,         fontWeight: 'bold',         marginBottom: 10,         color: '#6b52ae',     },     modalDescription: {         fontSize: 18,         textAlign: 'center',         marginBottom: 20,         color: '#555',     },     closeButton: {         backgroundColor: '#4a3',         padding: 12,         borderRadius: 8,         alignSelf: 'stretch',         alignItems: 'center',         marginTop: 10,     },     closeButtonText: {         color: '#fff',         fontWeight: 'bold',         fontSize: 16,     }, }); export default ImageCarousel; 

Steps to run the application:

Step 1: Run the App via the following command.

npx expo start

Step 2: Run the command according to your Operating System.

  • Android
npx react-native run-android
  • IOS
npx react-native run-ios

Output:




Next Article
Create an Image to Text App using React-Native

G

gauravggeeksforgeeks
Improve
Article Tags :
  • ReactJS
  • React-Native
  • React-Native-Questions

Similar Reads

  • Create an Image to Text App using React-Native
    In this article, we are going to build a step-by-step Image to Text app using React-Native. This application will allow users to extract the text from the image using OCR (Optical Character Recognition) and later copy it to the clipboard or share it with others. This application is a perfect usage o
    4 min read
  • Create a Camera App using React-Native
    A camera app using react native is a mobile application that is designed to capture photos or videos using the built-in camera functionality of a mobile device. In this article, you will learn how you can create a camera app with simple steps. Output Preview: Let us have a look at how the final appl
    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 ClassRoom App using React-Native
    ClassRoom App using React Native is a simple application designed to facilitate online learning and classroom management. These apps are commonly used in educational institutions, schools, colleges, and universities to enhance the teaching and learning experience. Preview of final output: Let us hav
    7 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 a Task Manager App using React-Native
    In this article, we'll walk you through the process of building a basic Task Manager app using React Native. The application enables users to effortlessly create, edit, complete/incomplete, and delete­ tasks, providing an uncomplicated yet impactful introduction to Re­act Native's mobile app develop
    7 min read
  • Create an E-commerce App using React-Native
    An E-commerce app using react native is an application designed to facilitate online buying and selling of goods and services. These apps aim to provide a digital platform for businesses to showcase their products or services and for consumers to browse, compare, and purchase items without the need
    5 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 Chatbot App using React-Native
    Creating a chatbot app using React Native will be an exciting project. In this article, we are going to implement a Chatbot App using React Native. Chatbot App is a mobile application that answers the user's questions on the basis of their previous learning or content provided by developers. It help
    4 min read
  • Create Job Board App using React-Native
    In this article, we are going to Create a Job Board App using React Native. The Job Board App is a simple application that is a collection of job openings in any field. It helps the students and the people who are searching for jobs in the market. It helps to find jobs and provides in-depth informat
    6 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