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
Resolve errors  |  Gmail  |  Google for Developers
What is the Carbon Cycle? What is the science behind it?
What Did Bimbo Airhead Reply When Asked
Pet For Sale Craigslist
Tyson Employee Paperless
Prosper TX Visitors Guide - Dallas Fort Worth Guide
Do you need a masters to work in private equity?
Craigslist Free Stuff Appleton Wisconsin
Lycoming County Docket Sheets
Snarky Tea Net Worth 2022
Roblox Character Added
Ktbs Payroll Login
Nier Automata Chapter Select Unlock
104 Whiley Road Lancaster Ohio
Mills and Main Street Tour
Nutrislice Menus
Wicked Local Plymouth Police Log 2022
U Break It Near Me
Van Buren County Arrests.org
Rimworld Prison Break
PCM.daily - Discussion Forum: Classique du Grand Duché
Which Sentence is Punctuated Correctly?
Hannaford Weekly Flyer Manchester Nh
Barista Breast Expansion
Pawn Shop Moline Il
fft - Fast Fourier transform
Buhl Park Summer Concert Series 2023 Schedule
130Nm In Ft Lbs
Rainfall Map Oklahoma
N.J. Hogenkamp Sons Funeral Home | Saint Henry, Ohio
Gridwords Factoring 1 Answers Pdf
Play 1v1 LOL 66 EZ → UNBLOCKED on 66games.io
Where Can I Cash A Huntington National Bank Check
Metro 72 Hour Extension 2022
4083519708
Myanswers Com Abc Resources
Hellgirl000
The Banshees Of Inisherin Showtimes Near Reading Cinemas Town Square
Nsav Investorshub
Simnet Jwu
Updates on removal of DePaul encampment | Press Releases | News | Newsroom
Craigslist Farm And Garden Reading Pa
Coroner Photos Timothy Treadwell
Autum Catholic Store
Strange World Showtimes Near Century Stadium 25 And Xd
N33.Ultipro
The Complete Uber Eats Delivery Driver Guide:
Turok: Dinosaur Hunter
Theater X Orange Heights Florida
O'reilly's On Marbach
Les BABAS EXOTIQUES façon Amaury Guichon
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.