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:
How to Implement Radio Button In React Native ?
Next article icon

How to Create Random Image in React Native ?

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

React Native has gained widespread popularity for its ability to create cross-platform applications using a single codebase. One interesting feature you might want to implement is displaying random images within your app. Whether you're building a gallery app or simply adding an element of surprise, generating random images can be an engaging feature. In this article, we will walk through the steps to create a random image generator in a React Native app.

Pre-requisites

  • Introduction to React Native
  • React Native Components
  • React Hooks
  • Expo CLI
  • Node.js and npm (Node Package Manager)

Steps to Create React Native Application

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

npx create-expo-app <<Project-Name>>

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

cd <<Project-Name>>

Project Structure:

Approach:

Create a random image generator in React Native by importing necessary components and hooks. Define an array of image URLs. Build a functional component using `useState` to manage image source. Implement a `generateRandomImage` function to select random URLs from the array. Apply styling using `StyleSheet.create` for a visually appealing layout. Render the component in your main app file, customizing the appearance to suit your app's design. This feature adds an engaging element to your app, from image galleries to interactive content, enhancing user experience and interaction.

Example: In this example, we will create random image generator.

  • App.js
JavaScript
import React, { useState } from 'react'; import { View, Image, Button, StyleSheet } from 'react-native';  const imageUrls = [     'https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png',     'https://media.geeksforgeeks.org/wp-content/uploads/20210224040124/JSBinCollaborativeJavaScriptDebugging6-300x160.png',     'https://media.geeksforgeeks.org/wp-content/uploads/20230816223732/geeksgforgeeks-logo.jpg',     'https://media.geeksforgeeks.org/wp-content/uploads/20230816223829/geeksgforgeeks-logo-1.png', ];  const App = () => {     const [imageSource, setImageSource] = useState('');      const generateRandomImage = () => {         const randomIndex =                Math.floor(Math.random() * imageUrls.length);         setImageSource(imageUrls[randomIndex]);     };      return (         <View style={styles.container}>             <View style={styles.imageContainer}>                 <Image source={{ uri: imageSource }}                         style={styles.image} />                 <Button title="Random Image"                          onPress={generateRandomImage} />             </View>         </View>     ); };  const styles = StyleSheet.create({     container: {         flex: 1,         justifyContent: 'center',         alignItems: 'center',     },     imageContainer: {         width: 300,         backgroundColor: '#ffffff',         borderRadius: 10,         elevation: 5, // For shadow on Android         shadowColor: '#000',         shadowOffset: { width: 0, height: 2 },         shadowOpacity: 0.2,         shadowRadius: 5,         padding: 20,         marginBottom: 20,     },     image: {         width: '100%',         height: 200,         marginBottom: 10,         borderRadius: 5,     }, });  export default App; 

Steps to Run:

To run react native application use the following command:

npx expo start

To run on Android:

npx react-native run-android

To run on Ios:

npx react-native run-ios

Output:


Next Article
How to Implement Radio Button In React Native ?
author
saurabhkumarsharma05
Improve
Article Tags :
  • Web Technologies
  • React-Native

Similar Reads

  • How to Cache Images in React Native?
    Caching images in React Native enhances app performance by reducing network load and improving image load times. By storing frequently accessed images locally, the app can quickly display them without needing to re-download, resulting in a smoother and faster user experience. Caching images in React
    2 min read
  • How to Generate Random Numbers in React Native ?
    Generating random numbers is a fundamental aspect of React Native development. It enables various functionalities like generating game elements, creating unique identifiers, and implementing randomized UI components. In this article, we are going to see how we can generate a random number by using R
    3 min read
  • How to Generate Random Password in React Native ?
    In this article, we'll explore the process of building a simple random password generator app using React Native­. The Math.random() me­thod is utilized to obtain a pseudo-random floating-point number ranging from 0 (inclusive­) to 1 (exclusive). The Math.floor() me­thod is used to round down a numb
    4 min read
  • How to Implement Radio Button In React Native ?
    In this article, we will learn to implement a Radio Button in React Native. A radio button signifies a graphical user interface­ element enabling individuals to make an exclusive se­lection among multiple alternative­s. React Native is a popular platform for creating native mobile apps for iOS and A
    11 min read
  • How to create toast in React Native ?
    React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows, and UWP by enabling developers to use the React framework along with native platform capabilities. In this article, we will
    2 min read
  • How to create Avatar in react-native ?
    React-native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render m
    2 min read
  • How to create a Surface in react-native ?
    React native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render m
    3 min read
  • How to Create Social Icons in React Native ?
    In this article, we will walk through the step-by-step process of creating and styling social icons in your React Native app. React Native­ emerges as a robust framework for building cross-platform applications effortlessly. By incorporating social icons into your React Native­ app. Social icons hav
    3 min read
  • How to Create Emoji Picker in React Native ?
    React Native is a popular cross-platform framework for mobile app development. Emojis have become common in modern applications, providing personalization and enhancing user engagement. In this article, we'll see how we can add an emoji picker to a React Native application. React Native doesn't have
    3 min read
  • How to set Background Image in react-native ?
    React Native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render m
    2 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