Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing Image URLs in React Native

I'm trying to set the image URL dynamically. The images are locally stored and their location paths are in a JSON file.

JSON File

{
  "total": 2,
  "categories": [
    {
      "id": "cat1",
      "name": "Burgers",
      "itemCount": 10,
      "images":{
        "main":"./../images/items/Burgers.jpg"
      }
    },
    {
      "id": "cat2",
      "name": "Pizzas",
      "itemCount": 5,
      "images":{
        "main":"./../images/items/Pizzas.jpg"
      }
    }
  ]
}

Code

renderItem: function (item) {
    var imageURL = require(item.images.main);
    return (
        <View style={styles.mainContainer}>
            <Image source={imageURL} style={styles.image}>
                <Text style={styles.textMain}>{item.name}</Text>
            </Image>
        </View>
    );
}

This gives the following error.

2015-12-10 16:02:45.295 [error][tid:com.facebook.React.RCTExceptionsManagerQueue] Unhandled JS Exception: Requiring unknown module "./../images/items/Burger.jpg". If you are sure the module is there, try restarting the packager.

But if I replace var imageURL = require(item.images.main); with var imageURL = require("./../images/items/Pizzas.jpg"); it shows the image perfectly.

What is causing this? How do this correctly?

like image 876
Nimila Hiranya Avatar asked Dec 19 '22 21:12

Nimila Hiranya


2 Answers

Using the require(PATH) method actually make the packager try and resolve the image during packaging which it can't do if its just looking at a variable. I would try doing:

<Image source={{uri: image.images.main}} />
like image 66
rmevans9 Avatar answered Jan 18 '23 06:01

rmevans9


We need to require the image before using it.

Something like this;

const image = require("../../assets/someImage.png");

<Image source={image} />

This thing worked for me.

like image 37
Mehul Thakkar Avatar answered Jan 18 '23 06:01

Mehul Thakkar