3

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", 
9
  • Did you try source={this.props.imageUri}? What is an eample value of this.props.imageUri? Are you trying to use a relative path or an absolute one? Commented Jun 3, 2018 at 15:26
  • And check stackoverflow.com/questions/36460827/… to see if it helps. Commented Jun 3, 2018 at 15:29
  • source={this.props.imageUri} - Yes, I did try it. I'm not getting any error but the image is not rendered. this.props.imageUri = ../assets/images/myImage.png Commented Jun 3, 2018 at 15:30
  • And check stackoverflow.com/questions/36460827/… to see if it helps - it doesn't help as I don't want to store my image into the state. There are about 100 possible combinations of images which may change in the future. I'm looking to send down the path from a Json/APi Commented Jun 3, 2018 at 15:34
  • You can't write a dynamic require statement like that, it says it in the error, it wants a string literal Commented Jun 3, 2018 at 15:42

1 Answer 1

6

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" /> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.