Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Error: Unknown named module', loading react-native image from a dynamic path

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?

like image 572
oillamp Avatar asked Mar 01 '16 01:03

oillamp


People also ask

How do I import an image into react native?

Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage. png) inside this folder. We will show images on the home screen.

How do I get an image from assets folder in React native?

Image In Class Component In React Native You can copy and paste from other folder. After that provide the path of that image inside the require which is a property of source of Image tag. Simply create an assets folder and paste the images there.


1 Answers

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

like image 70
Patrick Klitzke Avatar answered Oct 12 '22 11:10

Patrick Klitzke