Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native use variable for image file

I know that to use a static image in react native you need to do a require to that image specifically, but I am trying to load a random image based on a number. For example I have 100 images called img1.png - img100.png in my directory. I am trying to figure out a way to do the following

<Image source={require(`./img${Math.floor(Math.random() * 100)}.png`)}/> 

I know this intentionally does not work, but any workarounds would be greatly appreciated.

like image 269
bgrober Avatar asked Nov 25 '15 01:11

bgrober


1 Answers

For anyone getting to know the react-native beast, this should help :)

I visited a couple of sites in the past too, but found it increasingly frustrating. Until I read this site here.

It's a different approach but it eventually does pay off in the end. Basically, the best approach would be to load all your resources in one place. Consider the following structure

app      |--img       |--image1.jpg       |--image2.jpg       |--profile           |--profile.png           |--comments.png       |--index.js 

In index.js, you can do this:

const images = {     profile: {         profile: require('./profile/profile.png'),         comments: require('./profile/comments.png'),     },     image1: require('./image1.jpg'),     image2: require('./image2.jpg'), };  export default images; 

In your views, you have to import the images component like this:

import Images from './img/index';  render() {     <Image source={Images.profile.comments} /> } 

Everybody has different means to an end, just pick the one that suits you best.

Da Man - Q: How is this answer using a variable?

Well, since require only accepts a literal string, you can't use variables, concatenated strings, etc. This is the next best thing. Yes, it still is a lot of work, but now you can do something resembling the OP's question:

render() {   var images = { test100: "image100" };   return (     <View>       <Text>        test {images["test" + "100"]}       </Text>     </View>   ); } 
like image 186
DerpyNerd Avatar answered Sep 22 '22 15:09

DerpyNerd