600+ images. Dynamic path to image, require() syntax not working. best way?
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.
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.
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! :)
That solution was clutch.
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.