imagereact-nativepackager

React-Native: packager not detecting images


I can't figure out how to programmatically add in images in React-Native. I have a directory, /img, full of images, and a json file, data.json full of data entries that have corresponding and image file paths:

[
 {
  "id": "1",
  "img": "img1.png"
 },
 {
  "id": "2",
  "img": "img2.png"
 }
]

I have loaded data.json into a variable with var data = require('data.json'), and I can access the image paths normally through data[0].img. Also, I can create Image tags that display the images through <Image source={{uri = "./img/img1.png"}} style={styles.img}/>.

However, when I try to combine the two, with <Image source={{uri = "./img/" + data[0].img}} style={styles.img}/>, I get this error: Requiring unknown module "./img/img1.png". If you are sure the module is there, try restarting the packager.

I have restarted my simulator multiple times, searched here and the documentation for hours to figure out what I'm doing wrong. Any help would be greatly appreciated.


Solution

  • You have two "errors" in your code: object key is not assigned with = but with :. And you can't combine strings in this case, since AFAIK, there's ultimately used require() for images and it doesn't accept anything other but plain strings.

    I'd encourage you to do it like this:

    const assets = {
      img1: './img'+ data[0].img
    }
    
    ...
    
    <Image source={{uri: assets.img1} style={styles.img}/>