I've component in my application which works fine if it is assigned direct string value("someImage.png"), but if I try to assign it by storing image name in a local variable it gives this exception "require() must have a single string literal argument" This line works fine
<ImageBackground source={require("./Resources/bg/imageone.png")} resizeMode='cover' style={customStyles.backdrop}>
Issue occurs in this case
let imageName = "./Resources/bg/imageone.png";
<ImageBackground id="123" source={require(imageName)} resizeMode='cover' style={customStyles.backdrop}>
I also found same issue reported here, but no one has answered that yet. Can you help me out here?
This example of dynamic images can also show how to correctly assign a variable with the image source value. The recommendation is to assign the whole require
in a variable, instead of just its value.
// GOOD
<Image source={require('./my-icon.png')} />;
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;
// GOOD
var icon = this.props.active
? require('./my-icon-active.png')
: require('./my-icon-inactive.png');
<Image source={icon} />;
https://facebook.github.io/react-native/docs/images.html
Hope it helps
If you have indexes in the data then my approach to the issue is:
const image1 = require('../assets/images/image1.png');
const image2 = require('../assets/images/image2.png');
const image3 = require('../assets/images/image3.png');
const images = [image1, image2, image3];
...
<Image source={images[index]} />
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