Getting Started with React Native: Using Images in project

Getting Started with React Native: Using Images in project

So, Here I would be discussing how to handle Images In React Native we would be using the Image Component, images, including network images, static resources, temporary local images, and images from local disks, such as the camera roll. you need to import the Image component in your code and then need to give the image component it's the source (where the image is located)

// for loading images from a URL
      <Image source={{ uri: '', }} />
//for loading Images from assets in app
       <Image source={require('./assets/IamgeName.png')}/>
/*aslo you can directly add style  in Image component like any other component*/
     <Image style={styles.ImageStyle} source={require('@expo/snack-static/react-native-logo.png')} />

So now get started with the project we would be building a Dice Roller app.. for assets of dice you can download them from here .

now either you can use Expo or React Native on your pc or use snack in the browser. remember to download assets from here and upload them in the assets folder if you are using expo in the browser or place them in your project if you are coding on pc. so now we would be using StyleSheet, View, Image, TouchableOpacity so remember to import them in your project. also, we would be using useState to change state and update the dice image.

import React ,{useState}from 'react';
import { StyleSheet, View,Image ,TouchableOpacity } from 'react-native';

also import all images from the assets folder..

import Img1 from './assets/1.png';
import Img2 from './assets/2.png';
import Img3 from './assets/3.png';
import Img4 from './assets/4.png';
import Img5 from './assets/5.png';
import Img6 from './assets/6.png';

now inside the function component, we just need to add an image component and wrap it with touchableOpacity.

<View style={styles.container}>
      <TouchableOpacity >
      <StatusBar style="auto" />
      <Image source={Img1}/>


now we need to add a state to change the image so I will use the useState hook ..

  const [ImgAddress , setImgAddress]= useState(Img1);

also, time to replace the Img1 in the image source with ImgAddress. now I will use it onPress Prop of touchableOpacity to call a function diceRoll which will generate a random number and set a value of imgAddress between a number 1 to 6.

      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
![Black and Yellow Modern Social Media Marketing Trends Presentation.png](
      case 6:

If you want to view the full link here is the link to snack on the expo.

Did you find this article valuable?

Support Gaurav Tewari by becoming a sponsor. Any amount is appreciated!