Styykk Styykk - 4 months ago 37
Javascript Question

Printing an image for each object in an array with React Native

I'm pretty new to React Native and got stuck on a personal project trying to utilize Instagram's API. I'm currently using a forEach to try to return an Image for every object in an array and it doesn't seem like I can get the Image to show up. When I do a console.log(images.images.thumbnail.url) within the mediaPrinter function, I do see that all the urls are being logged.

Here's the API call:

export default function ApiCall() {
return fetch(url)
.then((response) => {
return response.json()
})
.then((json) => {
return json.data
})
.catch((error) => {
console.log(error)
})
}


And the rest of the relevant code:

mediaPage() {
return <ScrollView style={styles.scrollBody}>
<Text style={styles.welcome}>
Browse Through Our Moments
</Text>
<View style={styles.imageRow}>
{this.mediaHandler()}
</View>
</ScrollView>
}

mediaHandler() {
ApiCall()
.then((data) => {
this.mediaPrinter(data)
})
.catch((error) => {
console.log(error)
})
}

mediaPrinter(array) {
array.forEach(function(images) {
return <Image
source={{uri: images.images.thumbnail.url}}
style={{width: 138, height: 138}} />
})
}


I was also wondering if there was a way to resize the images responsively using React Native's currently provided resources.

Answer

This should do the tirck:

class renderImages extends Component {
  constructor () {
    super()
    this.state = {
      images: []
    }
  }
  
  componentDidMount () {
    this.mediaHandler()
  }
  
  mediaPage() {
  return <ScrollView style={styles.scrollBody}>
      <Text style={styles.welcome}>
          Browse Through Our Moments
      </Text>
      <View style={styles.imageRow}>
        {this.mediaPrinter(this.state.images)}
      </View>
    </ScrollView>
}

mediaHandler() {
  ApiCall()
    .then((data) => {
    this.setState({images: data})
      //this.mediaPrinter(data)
    })
    .catch((error) => {
      console.log(error)
    })
}

mediaPrinter(array) {
  return array.map(function(images, index) {
    // don't put your key as index, choose other unique values as your key.
    return <Image
      key={index}
      source={{uri: images.images.thumbnail.url}}
      style={{width: 138, height: 138}} />
  })
}

}

The function you called inside the <View style={styles.imageRow}></View> should return jsx to be rendered. As you can see, in your approach, you are returning nothing.

In the solution above, I have set the state when medialHandler gets data from instagram, which triggers the re-render and the mediaPrinter function is called again with the array of instagram photos data, hence it gets rendered.

Comments