How to use local Images dynamically in React Native (2024)

During Corna Home arrest, I developed a puzzle/Riddle application BrainBite. While developing I came across a strange issue which I had never expected in React Native. Brainbite is a riddle applications, where initially we thought of having puzzles created in a beautiful local image and showing it one after another. We had created around 50 Images with Images named numerically in ascending order. Ex: 1.png, 2.png …50.png etc.

Coming from Angular/Ionic background there was no complexity in implementing it, where I would generally write the file path as constant and take Image name dynamically.

Ex: const ImageDirectory = “Resources/Images”

const ImageName = currentIndex + “.png” //where current Index will be 1,2 etc.

Const ImagePath = ImageDirectory + ImageName

Since React too is Javascript framework, I was expecting something similar, with syntax change w.r.t React Native. But It was totally different.

Sample Code to display Image which are stored locally in React Native.

<Image

source={require(‘../Resources/Images/1.jpg’)}

style={{ width: 400, height: 350 }}

/>

Consider we create a state variable named ImagePath which changes depending on the current state of the application.

ImagePath: ‘../Resources/Images/1.jpg’ //default value

When user clicks on next button

nextPuzzle = () => {

this.state.setState({

ImagePath: ‘../Resources/Images/’ + currentIndex + ‘.png’

})

}

In the render method

<Image

source={require(ImagePath)}

style={{ width: 400, height: 350 }}

/>

But it failed. No Image was rendered when I call nextPuzzle event. And below error was thrown. The reason for this behavior is documented in this link.

How to use local Images dynamically in React Native (2)

And If I have to summaries the reason is

“The only allowed way to refer to an image in the bundle is to literally write require(‘image!name-of-the-asset’) in the source.”

In case your thinking, what is this error message is, It means in react all the static Image path has to be specified during the compilation itself, anything specified dynamically is considered as an error. They also recommend if the number of Images that your using locally exceeds certain number, then push it to your server and refer the path in the application. That time it uses Source as URI so there is no problem in loading such data.

But your app is something similar to fine and you want to load static Images dynamically then refer below steps. Though it looks tedious, this is the only solution that worked for me.

For quick solution refer this Stackoverflow link of my answer. For elaborated explanation read below.

  1. First create a folder named Resources/Images and place all your images there.
  2. Now create a file named Index.js (at Resources/Images) which is responsible for Indexing all the images in the Reources/Images folder. Below is the example content of Index.js file

const Images = {

‘image1’: require(‘./1.png’),

‘image2’: require(‘./2.png’),

‘image3’: require(‘./3.png’)

}

3. Now create a Component named ImageView at your choice of folder. One can create functional, class or constant component. I have used Const component. This file is responsible for returning the Image depending on the Index.

import React from 'react';
import { Image, Dimensions } from 'react-native';
import Images from './Index';
const ImageView = ({ index }) => {
return (
<Image
source={Images['image' + index]}
/>
)
}
export default ImageView;

4. Now from the component wherever you want to render the Static Images dynamically, just use the ImageView component and pass the index.

< ImageView index={this.qno + 1} />

In my example qno is the state variable that contains the current question number. And it changes when user clicks on Next and Previous button.

Hope this article is helpful, support me by giving claps and downloading the BrainBite application.

How to use local Images dynamically in React Native (2024)
Top Articles
Uber rival Grab raises $750M led by SoftBank at a $3B valuation | TechCrunch
How to Start Investing in Share Market with Rs 10,000 in India - Cash Overflow
Omega Pizza-Roast Beef -Seafood Middleton Menu
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Davita Internet
Skyward Houston County
Hawkeye 2021 123Movies
San Diego Terminal 2 Parking Promo Code
RuneScape guide: Capsarius soul farming made easy
2022 Apple Trade P36
Shaniki Hernandez Cam
City Of Spokane Code Enforcement
Infinite Campus Parent Portal Hall County
Savage X Fenty Wiki
Hope Swinimer Net Worth
Nene25 Sports
Love In The Air Ep 9 Eng Sub Dailymotion
London Ups Store
111 Cubic Inch To Cc
Imagetrend Inc, 20855 Kensington Blvd, Lakeville, MN 55044, US - MapQuest
Costco Gas Foster City
The Exorcist: Believer (2023) Showtimes
Vandymania Com Forums
Morristown Daily Record Obituary
Cb2 South Coast Plaza
Papa Johns Mear Me
HP PARTSURFER - spare part search portal
Sam's Club Gas Price Hilliard
2487872771
Issue Monday, September 23, 2024
Rogold Extension
Shiftwizard Login Johnston
Mg Char Grill
Kagtwt
Ma Scratch Tickets Codes
Mississippi weather man flees studio during tornado - video
Weekly Math Review Q2 7 Answer Key
At Home Hourly Pay
Craigslist Food And Beverage Jobs Chicago
13 Fun &amp; Best Things to Do in Hurricane, Utah
The Great Brian Last
War Room Pandemic Rumble
Tyco Forums
Unblocked Games 6X Snow Rider
Page 5747 – Christianity Today
Oefenpakket & Hoorcolleges Diagnostiek | WorldSupporter
Latina Webcam Lesbian
Ewwwww Gif
Sleep Outfitters Springhurst
Karen Kripas Obituary
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 5709

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.