16

When i use the Image component in React-native, it works fine when I declare my image's path/source as an inline string:

 <Image
    style={styles.img}
    source={require('mypic.png')}
 />

But when I define the path as a variable like this:

 var img = 'mypic.png';
 <Image
    style={styles.img}
    source={require(img)}
 />

...it doesn't work. The error msg is "Error: unknown named module 'mypic.png'"

I have many images, and I need to require them dynamically. There are too many to write manual import statements to require them one-by-one.

Even with a simple toggle like this one, it's far less efficient:

var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');

How do people usually solve for dynamic loading of variable images?

XML
  • 19,206
  • 9
  • 64
  • 65
oillamp
  • 201
  • 1
  • 2
  • 5

1 Answers1

23

You cannot do dynamic static images, so you can either use uri or do static things like var test=require('image'). Have a look at this issue: https://github.com/facebook/react-native/issues/2481

Patrick Klitzke
  • 1,519
  • 2
  • 14
  • 24