0

Beginner with React Native here.

I'm working on a small App which needs to display an image according to a random number. For exemple if I got 203, I want to display the image Project/img/203.png (random number is between 1 and 726)

The first thing I tried was require(dynamicPath), after reading documentation I understood that was not a good way to do it and I don't want to require each 726 image staticly. Then I tried with the uri syntax :

//Executed from Project/components/ folder
loadImage(number){
  imgUri = '../img/'+number.toString()+'.png'  
  return(
    <Image source={{uri: imgUri}} />
)

The application does launch but there is no image displayed (even with height/width style set). Examples I had seen with uri syntax were about images recieved from a web URL so I'm not sure it allows to get it from a local storage, but i can not find another way to get the image.

Axahox
  • 31
  • 4
  • Possible duplicate of [React Native - Image Require Module using Dynamic Names](https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names) – Muhammad Mehar May 20 '19 at 00:21

2 Answers2

0

The general rule is you can't use dynamic string for require (check the link in Muhammad Mehar's comment for detail), thus you need to store all required images into an array:

const images = [
  require('../img/1.png'),
  require('../img/2.png'),
  ...
  require('../img/726.png'),
];

loadImage(number){
  return <Image source={images[number-1]} />
}

Of course you can generate the code lines for the array and copy it to the editor to save time.

roel
  • 1,640
  • 14
  • 13
  • Thanks for answer ! Indeed I finally generated a function which is basically a switch/case with 726 entries to require each image when I need it. I'm very surprised there is no way to do it in an easier way but I guess there is a good reason – Axahox May 25 '19 at 20:26
-1

Switch case is garbage. Use template literals.

loadImage(number){
  imgPath = `../img/${number.toString()}.png` 
  return(
    <Image source={require(imgPath)} />
)
sonicmario
  • 601
  • 8
  • 22