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?
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}} />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With