I want to load an image based on the state which I am getting from API call. For example, if the API gives me '1'
, I want to load 1.png
. Unfortunately I am getting the above error.
Here is my code
let img = info.WeatherIcon ? require(`../../img/icons/${info.WeatherIcon}.png`) : require('../../img/icons/7.png')
< Image style = {{ width:120, height:120}} source = { img } />
You can't use dynamic links. According to React-Native, all your image sources need to be loaded before compiling your bundle.
So change your code as below,
let img =
info.WeatherIcon == "1"
? require("../../img/icons/1.png")
: require("../../img/icons/7.png");
then you can render your Image
<Image style={{ width: 120, height: 120 }} source={img} />
For more complicate example you can use condition as below,
switch (info.WeatherIcon) {
case "1":
return require("../../img/icons/1.png");
case "2":
return require("../../img/icons/2.png");
case "3":
return require("../../img/icons/3.png");
default:
return require("../../img/icons/7.png");
}
Hope this helps you. Feel free for doubts