0

i have saved images names in state but when i try to show them its giving the error 'Invalid call require('./assets/'+this.state.img1)' ( but when i put the image name directly in source its start working. Like : i have also alert the state its having the same image name.

  render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img1)}
      />
       <Image
        style={styles.stretch}
        source={require('./assets/'+this.state.img2)}
      />
    </TouchableOpacity>
  )
}
Nadeem
  • 261
  • 1
  • 4
  • 19

1 Answers1

2

According to the documentation : In order for this to work, the image name in require has to be known statically.

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

What you can do is building a mapping/object :

const myImages = {
  img1: require('/path/to/img1'),
  img2: require('/path/to/img2'),
};

render() {
  return (
  <TouchableOpacity onPress={this.onItemPressed} style={styles.container}>

       <Image
        style={styles.stretch}
        source={myImages[this.state.img1]}
      />
       <Image
        style={styles.stretch}
        source={myImages[this.state.img2]}
      />
    </TouchableOpacity>
  )
}

For this to work, this.state.img1 and this.state.img2 must be a key in the object myImages.

TBouder
  • 2,539
  • 1
  • 14
  • 29