react-nativetouchableopacityimagebackground

ImageBackground not working when i call source from state


ImageBackground does not show the image when I called source from state.

I tried to use a conditional statement like at first touchable opacity but not working again.

state = {
    color1: "../images/yellow-orb.png",
    color2: "../images/yellow-orb.png",
}
<TouchableOpacity onPress={() => this.questSelect(1)}>
          {this.state.color1 ? (
            <ImageBackground
              source={{ uri: this.state.color1 }}
              style={styles.icon2}
            >
              <Text>1</Text>
            </ImageBackground>
          ) : (
            null
          )}
</TouchableOpacity>
<TouchableOpacity onPress={() => this.questSelect(2)}>
          <ImageBackground
            source={{ uri: this.state.color2 }}
            style={styles.icon2}
          >
            <Text>2</Text>
          </ImageBackground>
</TouchableOpacity>

At emulator, I can see texts like 1 2 3 .. but there aren't images.


Solution

  • You need to add require() in order to load from source.

    eg:

     <ImageBackground
                  source={require("../images/yellow-orb.png")}
                  style={styles.icon2}
                >
                  <Text>1</Text>
     </ImageBackground>
    

    OR

    update your state like this,

    this.state = {
        color1: require("../images/yellow-orb.png"),
        color2: require("../images/yellow-orb.png"),
    }
    

    and use state value directly,

     <ImageBackground
                  source={this.state.color1}
                  style={styles.icon2}
                >
    

    please check