1

I tried almost every solution from stackoverflow & github, But unfortunately nothing is working to me !

I need to render image according to an click event. My app is fine when i put the hard coded require value like this

<Image style={{width: 50, height: 50}} source={require('./hulk.png')} />

But it doesn't work if i store the value to a variable and then put this variable into the require like this

let legendPic = `./${this.props.title.toLowerCase()}.png`;
........
<Image style={{width: 50, height: 50}} source={require(legendPic)} />

Here is the my renderDescription method's code

renderDescription = () => {
    if(this.props.id === this.props.selectedLibraryId) {
      let legendPic = `./${this.props.title.toLowerCase()}.png`;
      console.log(legendPic);
      return(
        <CardSection>
          <Image 
            style={{height: 50, width: 50}} 
            //source={require(legendPic)} 
          />
          <Animatable.Text animation='lightSpeedIn'>{this.props.description}</Animatable.Text>
        </CardSection>
      );
    }
  }

From the console i get the desired output, but it doesn't work with require.

This is my simple app, when i click any title - description will appear. Left empty space is to show image but i can't solve this issue anymore. Screen Shot of App

I tried all the possible solution from here stackoverflow

Console Output: enter image description here

In case you want to see the whole source code Github Link

Thank's

Robin
  • 4,902
  • 2
  • 27
  • 43
  • Are you sure you've tried [this solution](https://stackoverflow.com/a/42245762/7581249)? – Milore Mar 18 '19 at 09:35
  • @Milore yes, it works when i use path as a string like require('./hulk.png'), but when i use a variable with string literal instead of string it doesn't work :( – Robin Mar 18 '19 at 09:42
  • Possible duplicate of [React Native - Image Require Module using Dynamic Names](https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names) That is because `react-native` currently doesn't support using dynamic strings for `require` making this question a duplicate – Andrew Mar 18 '19 at 10:26

1 Answers1

0

you should include all required assets into an object like this:

const assets = {
  key: require('./path-to-image'),
  key2: require('./path-to-image'),
  key3: require('./path-to-image'),
}

where you name your keys based on your props.title

and then you change your image dynamically from that object like this:

renderDescription = () => {
    if(this.props.id === this.props.selectedLibraryId) {
      let legendPic = assets[this.props.title.toLowerCase()];
      console.log(legendPic);
      return(
        <CardSection>
          <Image 
            style={{height: 50, width: 50}} 
            source={legendPic} 
          />
          <Animatable.Text animation='lightSpeedIn'>{this.props.description}</Animatable.Text>
        </CardSection>
      );
    }
  }