0

enter image description here

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 } /> 
Godwhacker
  • 3,624
  • 3
  • 15
  • 23
Muhammad Sami
  • 520
  • 2
  • 8
  • 21

1 Answers1

0

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

SDushan
  • 4,341
  • 2
  • 16
  • 34
  • i have more than 50 images.. Its tedious work? any other Alternative? – Muhammad Sami Apr 01 '20 at 14:09
  • @MuhammadSami that's how react-native works. but you can try to create a custom component to render an image using ```react.PureComponent``` or ```react.memo``` when passing an individual image from API. – SDushan Apr 01 '20 at 14:47