Home Ask Login Register

Developers Planet

Your answer is one click away!

Cherniv February 2016

Image preloading in React Native

I am building my first app with React Native, an app with a long list of images. I want to show a spinner instead of image while image is loading. It is sounds trivial but i didn't found a solution. I think for a spinner i suppose to use ActivityIndicatorIOS , but how am i combining it with an Image component?

<Image source={...}>
  <ActivityIndicatorIOS />

Is this a right direction? Am i missing something?


dvine multimedia February 2016

Just ran into the same issue. So basically you have the correct approach, but the indicator should of course only be rendered when the image is loading. To keep track of that you need state. To keep it simple we assume you have just on image in the component an keep the state for it in the same component. (The cool kids will argue you should use a higher order component for that and then pass the state in via a prop ;)

The idea then is, that your image starts out loading and onLoadEnd (or onLoad, but then the spinner gets stuck on error, which is fine or course) you re-set the state.

getInitialState: function(){ return { loading: true }}

render: function(){
    <Image source={...} onLoadEnd={ ()=>{ this.setState({ loading: false }) }>
        <ActivityIndicatorIOS animating={ this.state.loading }/>

You could also start out with { loading: false } and set it true onLoadStart, but I'm not sure what the benefit would be of that.

Also for styling reasons, depending on your layout, you might need to put the indicator in a container view that is absolutely positioned. But you get the idea.

Post Status

Asked in February 2016
Viewed 2,616 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life