Adding image placeholders in react native the right way


When developing applications in react native we often use image element which load images from some url. On faster networks and simple applications the images load gracefully and we generally don’t need to add image placeholders. However on slower connections andlike news,media and ecommerce applications which have long image grids or multiple image containers in scrollviews  it becomes imperative to add image placeholders until the image is loaded in the app from url.

My first preferred approach was to defaultSource property available in Image element in react native.However it is currently available in ios and my app is mainly focused towards android community so that was out of question. I found one npm module which added defaultSource support to android but it did not work properly in my case. Finally I stumbled across an article which explained creation of custom placeholder component in ES5 syntax and converted the code to es6 without much efforts. Without boring you further with the background story lets start coding:

First we will add a small delay to loading of image using animated api to give the user a fading effect while image is rendered.Create a progressiveImage.js within folder where you keep your reusable components:

I am using redux in my project and you can simply export the class  without using redux functions.Use the image component in your app as follows:

Now let us modify progressiveImage component to add placeholder view which gets replaced by image once it loaded through url:

Add thumbnail property to your implementation as follows:

I would recommend keeping the placeholder/thumbnail image in the app itself for loading it even when app is offline so that user at least sees placeholder image instead of a blank view.

That’s it for today’s tutorial. You can read the original article from which this tutorial is heavily borrowed here. If anyone is interested in creating a better npm module out of this or know about one already then feel free to mention it in the comments section or ping me on facebook or medium.

Connect Deeper:

You can follow our facebook page to get notified about similar such articles in the future: Technoetics

Image source:Pixabay

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development