suman j
suman j

Reputation: 6980

react native require not working for image source

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.

Upvotes: 4

Views: 13156

Answers (2)

psycho
psycho

Reputation: 31

make sure give some style like this

<Image source={{uri: 'https://reactjs.org/logo-og.png'}} style={{width: 400, height: 400}} />

Upvotes: 2

Konstantin Kuznetsov
Konstantin Kuznetsov

Reputation: 903

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} />

Upvotes: 6

Related Questions