1

I tried to display an image from a local file, so I try to do this

<Image 
    source={{uri:'../../assets/img_src/BTI.jpg'}}
    style={{height:150,width:150}}
/>

my container component seems getting the height and the width but the image doesn't load. So I try this

<Image 
    source={require('../../assets/img_src/BTI.jpg')}
    style={{height:150,width:150}}
/>

It works really well, unfortunately as far as I know I can't use this implementation if i want to manipulate the address file first and store it to a variable. Example:

const imgSrc = `../../assets/${data.image}`;

where the data.image = 'img_src/BTI.jpg'. I try to delete all the data on my android simulator in the android studio but the result is still the same. Am I doing something wrong? Is there a better implementation for this?

Thanks a lot :)

Jitender
  • 7,593
  • 30
  • 104
  • 210
Irvan
  • 165
  • 1
  • 13
  • You mean you cannot use source={require(imgSrc)}? – Hariks Mar 27 '17 at 15:51
  • It looks like this is happening because you're trying to include an asset using a variable name as the source. The accepted answer here gives some insight into why this doesn't work: http://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names#30868078 – QMFNP Mar 27 '17 at 16:27
  • @Hariks yeah, an error message will appear – Irvan Mar 28 '17 at 12:31

1 Answers1

13

Not being able to require() a dynamic path is an intended behaviour of React Native, the packager needs to know paths in advance - see React Native issues

We had this problem in our project, we were storing image URLs on our DB and wanted to concat strings in the app to get the path to the locally stored image. As you've discovered, this doesn't work. You might find our workaround useful.

In our /images folder, we created a new images.js file which simply exported an object whose keys mapped to all our local image paths like so

  export const Images = {
    image1: require('./image1.png'),
    image2: require('./image2.png'),
    image3: require('./image3.png'),
  };

Now the packager knew all the paths in advance and was happy. Then we added an imageKey to the DB item and used this rather than the absolute path. To grab an image we simply did

import { Images } from '../images/images';
// get your image key e.g. passed down through props
const img = Images[imageKey];

...
render() {
    ...
    <Image source={img} />
    ...
}

Might not fit your exact use case, but hopefully you might be able to make some use of it.

cortexlock
  • 1,446
  • 2
  • 13
  • 26
  • Was having the same problem in my project, so I tried @drjimmie1976 solution and it Worked perfectly, I only change the file name to `index.js` under the `/images` folder so I can call it shorter as `import { Images } from '../images';` but other way exactly as @drjimmie1976 said. – rodrigogiraudo May 17 '19 at 21:43