How to create an Asynchronous Image loading component in React Native

React Native is a great technology for creating purely native Android and IOS apps. but sometimes we get into trouble specially in case where there is too much data to render or handle in addition that data is coming from some source from internet, it may take some time to load.

specially in case of Images as data or part of data, what i have experienced is if Images are loaded from some url it may take time for Image to load and then only we are able to see that Image on screen.

According to UI and UX it is not good as we don’t know when it will load completely and we will be able to see that on screen. so for a good UX we must render something / Placeholder in place of Image until and unless Image is completely loaded and rendered on screen.

 

React Native Asynchronous Image Loading Component

A demonstration of the image component we will be creating

from the above image we can see a good practice when creating user experiences, display a placeholder in place of an image while it’s loaded from the network. By doing so our apps feel faster to the user and get background tasks out of the way so users can accomplish their goals.

 

So in this tutorial of React Native you are going to learn how to create your own Asynchronous Image loading component and make your app looks and feel good for your users. without wasting anymore time let’s dive into it’s making.

 

our very first step is to create a Basic React Native Component with a <View></View> component to render on screen here is how we create a component in React Native.

import React, { Component } from 'react';
import { View, Image } from 'react-native';

export default class AsyncImage extends Component {

render() {
        return (
            <View>
               //async image component will go here later
            </View>
        )
    }
}

so what we see here is a basic React Native component with a <View></View>. to render on screen.

now let’s add props to it so as to make it reusable for our whole app or to be usable in other apps also.

below is code after adding props to this AsyncImage class / component.

import React, { Component } from 'react';
import { View, Image } from 'react-native';

export default class AsyncImage extends Component {
    //added constructor in class so as to declare state and get props from parent
    constructor(props) {
        super(props)
        this.state = { loaded: false }
    }

    render() {
        //extracting properties from props passed from parent.
        const {
          placeholderColor,
            style,
            source
        } = this.props
        return (
            <View style={style}>
                //async image component will go here
            </View>
        )
    }
}

so here we have declared a constructor for our component to create a state component.

and we are extracting properties from this.props to use in our component.

don’t know how to extract properties from a javascript object in single line of code ? well here is explanation of what i have done in above code.

let suppose we have a javascript object named as  –  obj = {};

it has 2 properties say – {a: 1, b: 2};

so if we want to extract a from obj we have two methods –

  • var prop1 = obj.a;    – this will give value of a to prop1.
  • var {a} = obj;            –  by this we have extracted value of a from obj and we can now use a as our new variable.

 

Now it’s time to add a image to our <View></View> component so as we can see something on screen not just blank space.

code after adding <Image/> component inside our View component.

import React, { Component } from 'react';
import { View, Image } from 'react-native';

export default class AsyncImage extends Component {
    //constructor to declare state and get props from parent
    constructor(props) {
        super(props)
        this.state = { loaded: false }
    }

    render() {
        //extracting properties from props passed from parent.
        const {
          placeholderColor,
            style,
            source
        } = this.props
        return (
            <View style={style}>
                    //Image Component
                    <Image
                        source={source}
                        resizeMode={'cover'}
                        style={[
                            {
                                position: 'absolute',
                                resizeMode: 'cover'
                            },
                            style
                        ]} />
            </View>
        )
    }
}

So in above code we have added a <Image/> component from react native with source as dynamic component i.e source will be provided from parent in which we will use this component to render a Async Image.

styling we have used 2 properties as static for every image. and rest style we are loading from props. so how will image look totally depends on style passed as props from parent.

 

wondering where is the placeholder and magic to make it Asynchronous huh? don’t worry below is the code and explanation to make this component purely Async.

 

Below is the code after adding Placeholder & Async Loading Function. to this component

import React, { Component } from 'react';
import { View, Image } from 'react-native';

export default class AsyncImage extends Component {
    //constructor to declare state and get props from parent
    constructor(props) {
        super(props)
        this.state = { loaded: false }
    }

    render() {
        //extracting properties from props
        const {
          placeholderColor,
            style,
            source
        } = this.props
        return (
            <View
                style={style}>
                    <Image
                        source={source}
                        resizeMode={'cover'}
                        style={[
                            {
                                position: 'absolute',
                                resizeMode: 'cover'
                            },
                            style
                        ]}
                        onLoad={this._onLoad}  //function which will call after image loads completely
                        />
                //render place holder until and unless image loading state changes.
                {!this.state.loaded &&
                    <Image source={require('../Images/user.png')} style={style} />
                }
            </View>
        )
    }
    //Function to set state for image loading status.
    _onLoad = () => {
        this.setState(() => ({ loaded: true }))
    }
}

 

so above is the complete code for our Async Image Loading Component.

what we have done is we have used image onLoad function to know whether image loaded or not. when image loaded it set state to loaded and we stop rendering placeholder. and we can see loaded Image.

source of place holder is from local so it does not take time to render. we can also make it dynamic to render different place holder on different places. it totally depends on our imagination and use cases.

 

now just import this component in any of your component and pass styling and other props accordingly to see it in action.

 


Likes this article?  don’t forget to subscribe to our newsletter so as to get updates for new posts from CodingIsEasy. do share and comments and let us know on what topics we should write to make your React Native Development a Cake Walk!


Happy Coding

 

You may also like...

1 Response

Leave a Reply to bXNcfJGetKWPIMCU Cancel reply

Your email address will not be published. Required fields are marked *