Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require() must have a single string literal argument React Native

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?

like image 300
Zubair Avatar asked Dec 19 '17 13:12

Zubair


2 Answers

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

like image 161
soutot Avatar answered Nov 04 '22 12:11

soutot


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]} />
like image 8
Onuray Sahin Avatar answered Nov 04 '22 13:11

Onuray Sahin