React native detect loading image

4.1k Views Asked by At

I have a problem. I use onLoad, onLoadStart and onLoadEnd in Image. I want to wait while server get response link image and show image, add loading. But its jerking constantly.

  constructor (props) {
    super(props)
    this.state = {loading: true}}

    return(
     <Image
        onLoad={(e) => this.setState({loading: true})}
        onError={(e) => this.setState({loading: false})}
        onLoadStart={(e) => this.setState({loading: false})}

        source={this.state.loading ? require('../../img/loading.gif') : { 
         uri: getBestUrl(artwork)}}
        style={styles.artworkImage}
        resizeMode={Image.resizeMode.cover}
      />)
1

There are 1 best solutions below

1
On

Are you returning an image from your constructor or you didn't post all the code?

Now to the question, I think it won't work that way since it seems that will always change the state while it's loading your 'loading.gif' or your uri image. Also are you setting a height and weight to your image? This is needed as you can see in the docs

Unlike with static resources, you will need to manually specify the dimensions of your image.

https://facebook.github.io/react-native/docs/images.html#network-images

Maybe you can store the image path in your state and make a conditional rendering according to the state value. For example:

...
this.state = {
imagePath: null,
}
...

this.setState({
imagePath: getBestUrl(artwork);
});
...

{
this.state.imagePath ? <Image uri={require(this.state.imagePath)} /> : <Image uri={require('loading.gif')}
}

Consider the code above just as an example to express the idea.

Hope this can be worth for you.