Reputation: 503
I'm trying to render a list of images from a base component by sending down title and image URL.
Everything works fine if I'm rendering the images like this:
<Image source={require('../assets/images/myImage.png')} />
The issue is coming when I'm trying to render the image from props:
class ListItem extends Component {
render() {
return (
<View>
<Text>{this.props.title}<Text>
<Image source={require(this.props.imageUri)} />
</View>
);
}
};
ListItem.propTypes = {
title: PropTypes.string.isRequired,
imageUri: PropTypes.string.isRequired,
};
As a result, I'm getting the next error:
calls to
require
expect exactly 1 string literal argument, but this was found:require(this.props.imageUri)
.
I've also tried to render the images using uri
<Image source={{uri: this.props.imageUri}} />
package.js
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",
Upvotes: 3
Views: 4196
Reputation: 66315
If you're using remote images with uri
they can be dynamic but require
for local images needs to resolve the paths at build time so they can't be. Create a hash of known paths:
const imageNames = {
apple: require('./images/apple.png'),
orange: require('./images/orange.png'),
};
And refer to them by their name:
class ListItem extends Component {
render() {
return (
<View>
<Text>{this.props.title}<Text>
<Image source={imageNames[this.props.imageName]} />
</View>
);
}
};
ListItem.propTypes = {
title: PropTypes.string.isRequired,
imageName: PropTypes.oneOf(Object.keys(imageNames)),
};
// e.g.
<ListItem imageName="orange" />
Upvotes: 6