react-native icon indicating copy to clipboard operation
react-native copied to clipboard

600+ images. Dynamic path to image, require() syntax not working. best way?

Open liesislukas opened this issue 11 years ago • 4 comments

Hi, I'm building Android app with 600+ images. Image is loaded according to selected settings, i of course can write if/else or switch loops with 600 if clauses, but that sounds painful already, so i have function "getCurrentImage" and it return string to image path like:

Work:

<Image style={styles.image} source={require('./../../img/grey_c_red_standard_2.jpg')}/>

Do not work:

<Image style={styles.image} source={require(this.getCurrentImage(this.props.state))}/>

Function returns same string as from static example. What is best way to handle so much images?

I can make it work moving all those dynamic images to android/app/src/main/res/drawable folder and running react-native run-android again. But looking for better way. Haven't started iOS developing, but i think I will have to make same app for iOS too, so i would like to have one location for both - Android and iOS.

liesislukas avatar Nov 09 '15 15:11 liesislukas

A nice approach is to write a script that generates a big lookup table for you. The idea is you'd generate a map like this:

/* images.js */
export default {
  grey_c_red_standard_2: require('./../../img/grey_c_red_standard_2.jpg'),
  /* etc... */
};

Then you could easily index into the map at runtime (require('images')[imageName]) while satisfying the packager's requirement that all image paths are statically specified up front.

ide avatar Nov 09 '15 18:11 ide

That could be an option! I can write small script to scan img dir and generate all 600+ lines with paths :+1: If I will have to write iOS app, will use this approach. Now I'll leave as it is in drawable folder. Thank you, James! :)

liesislukas avatar Nov 09 '15 19:11 liesislukas

That solution was clutch.

RFSync avatar May 04 '17 02:05 RFSync

Working solution. Thanks for this @liesislukas. Now how do we make this issue appear or somehow rank higher when developers encounter similar issues similar to this and are looking all over on github issues or google.

kanalasumant avatar Dec 28 '17 23:12 kanalasumant