0

In my React Native app, I have a component that contains an Image whose source I want to depend on an input prop. I've tried the following two methods:

<Image source={require('@images/'+this.props.image+'.png')}/>

and

<Image source={require(this.props.image === 'a' ? '@images/a.png' : '@images/b.png')}/>

but both throw errors. Can anyone tell me what's wrong with these pieces of code? The only other solution I can think of is

<Image source={require(this.props.image)}/>

and to pass in the pathname of the image as a prop, but I assume there's a cleaner solution.

RNdev
  • 953
  • 1
  • 8
  • 26

2 Answers2

0

You are seeing such error because according to React-Native, all your image sources need to be loaded before compiling your bundle. You can learn more about Images

You can solve this using below approach

let icon = this.props.image === 'a'
    ? require('./images/a.png')
    : require('./images/a.png');

<Image source={icon} style={{ width: 40, height: 40 }} />;

Hope this helps you. Feel free for doubts.

SDushan
  • 4,341
  • 2
  • 16
  • 34
0

There is no way to load static image dynamically in react native. So, you have to load all the static image that you want to use. For that you can create a variable that hold the image, which you can use after the load. For ex :

const imageA = require('@images/a.png');
const imageB = require('@images/b.png');

then, when you want to use image :

<Image source={this.props.image === 'a' ? imageA : imageB )}/>

Note : You have to load all the images that you want to use.

Kishan Bharda
  • 5,446
  • 3
  • 30
  • 57