Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native require not working for image source

Tags:

react-native

Given below code, react native complains

Requiring unknown module "../../images/Foo.png".If you are sure the module is there, try restarting the packager or running "npm install".

But the same code works fine if I hardcode the image source path in require call.

Code not working: has a method call to determine icon name. Notice the require('../../images/'+imageIconNameFor(prediction.type) line.

const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
    <View style={styles.predictionItem}>
        <Image style={styles.predictionIcon} source={require('../../images/'+imageIconNameFor(prediction.type))}></Image>
    </View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
    return "Foo.png";
}

Code working: Instead of calling a method to determine icon name, if I hardcode the icon name in require call, it works fine. Notice the require('../../images/Foo.png') line.

const PredictionItem = ({prediction}) => (
<TouchableHighlight onPress={() => itemPressed()}>
    <View style={styles.predictionItem}>
        <Image style={styles.predictionIcon} source={require('../../images/Foo.png')}></Image>
    </View>
</TouchableHighlight>
);
function imageIconNameFor(predictionType) {
    return "Foo.png";
}

Why is there a different behavior when I concatenate strings to build image source?
Why require('../../images/'+imageIconNameFor(prediction.type) fails to render image but require('../../images/Foo.png') works fine?

Note that method call was not a problem. Error message contains the complete path of the image computed using the method call. In spite of the complete path, react native complained about missing module with require.
React native version is 0.37.0. I tested this on ios-simulator.

like image 486
suman j Avatar asked Oct 20 '25 17:10

suman j


1 Answers

Unfortunately, this is how react-native packager works, the image name in require has to be known statically. Here is example from official docs:

// 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} />
like image 117
Konstantin Kuznetsov Avatar answered Oct 22 '25 19:10

Konstantin Kuznetsov