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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With