0

I'm trying to generate a random card image - depending on the string returned from this.generateRandomCard - but I'm getting the following error:

"Requiring unknown module "./card_images/7S.png". If you are sure the module is there, try restarting the packager or running "npm install".

Note: Using require('./card_images/7S.png') works.

Here is my code:

render: function() {
  var card = require('./card_images/' + this.generateRandomCard() + '.png');
  return (
    <View>
      <Text>{this.generateRandomCard()}</Text>
      <Image source={card}/>
    </View>
  );
}

Thanks for the help!

JLeemur
  • 3
  • 3
  • possible duplicate http://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names see this link about dynamic requiring https://github.com/facebook/react-native/issues/2481 – LHIOUI Jun 26 '16 at 23:37

1 Answers1

1

you should randomise it in another way! for example like this:

//define a list of images in component constructor
this.rImages = [require('random/image1.png'),require('random/image2.png'), ... etc]

Then in render function

//generate random integer between 0 and rImages.length
var randomInt = Math.floor(Math.random() * this.rImages.length)
var rImage = this.rImages[randomInt]
<Image source={rImage}/>
LHIOUI
  • 3,287
  • 2
  • 24
  • 37