Dynamically changing Image URLs in React Native

12,155

Solution 1

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}} />

Solution 2

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.

Share:
12,155
Nimila Hiranya
Author by

Nimila Hiranya

Not a bot. 🇱🇰

Updated on June 24, 2022

Comments

  • Nimila Hiranya
    Nimila Hiranya almost 2 years

    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?