7

I have this array of images in my project.

this.state.destinations = [{
    "destinationId": "001",
    "img": "../../assets/img/destinations/001.png"
  },
  {
    "destinationId": "002",
    "img": "../../assets/img/destinations/002.png"
  },
  {
    "destinationId": "003",
    "img": "../../assets/img/destinations/003.png"
  }]
}

I am trying to repeat each of them inside a View in a Image component like this:

render() {

    var {navigate} = this.props.navigation;

    return (
        <LinearGradient 
          colors={['#514A9D', '#24C6DC']} start={[0.0, 0.5]} end={[1.0, 0.5]} locations={[0.0, 1.0]} style={{flex:1}}>
            <ScrollView>
              {
                <View style={{paddingTop: 24}}>
                  {
                    this.state.destinations.map(dest => {
                      return <Image style={{height: 200, width: 600}} key={dest.destinationId} source={require(dest.img)} resizeMode="contain" />
                    })
                  }
                </View>
              }
            </ScrollView>
        </LinearGradient>
    );
  }

But I getting some crazy error in my phone when trying to run:

Error

I trying to run the app in expo and I am just developing it in react-native mode, not react-native-init mode.

2 Answers 2

13

Try refactoring your code in the following way, moving your use of require directly to where your data is defined so that the static resource path is evaluated correctly:

this.state.destinations = [{
    "destinationId": "001",
    "img": require("../../assets/img/destinations/001.png")
  },
  {
    "destinationId": "002",
    "img": require("../../assets/img/destinations/002.png")
  },
  {
    "destinationId": "003",
    "img": require("../../assets/img/destinations/003.png")
  }]
}

And then update the way you render <Image /> like so, removing the call to require() and referencing dest.img directly:

this.state.destinations.map(dest => {
  return <Image source={dest.img}
           key={dest.destinationId}
           style={{height: 200, width: 600}} 
           resizeMode='contain' />
})

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

You saved my day! However this should be treaten as a bug on side of image source. It resolves a string but not a mapped string inside require() ..weird behaviour.
3

Dynamic image import:

"img": require("../../assets/img/destinations/001.png")
<Image source={dest.img} />

Expo link: code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.