Image preloading in React Native

Ivan Chernykh picture Ivan Chernykh · Feb 8, 2016 · Viewed 19.9k times · Source

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 />
</Image>

Is this a right direction? Am i missing something?

Answer

LeonHeart picture LeonHeart · Sep 8, 2018

I will share my solution

<View>
    <Image source={{uri: this.state.avatar}} style={styles.maybeRenderImage}
                                   resizeMode={"contain"} onLoadStart={() => this.setState({loading: true})}
                                   onLoadEnd={() => {
                                       this.setState({loading: false})
    }}/>
    {this.state.loading && <LoadingView/>}
</View>

LoadingView.js

export default class LoadingView extends Component {
    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator size="small" color="#FFD700"/>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        position: "absolute",
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        opacity: 0.7,
        backgroundColor: "black",
        justifyContent: "center",
        alignItems: "center",
    }
});