React Native Display Default Source Image While Loading Main Image

Hi everyone, In this tutorial we will learn how to use defaultSource={} in Image component. This prop should show a placeholder image from local resource until the real image from network is loaded. But it doesn't work well, I don't know why. So I found a workaround solution that works fine. We will use a ternary operator with state in the image source. We will create a state and set its default value to false. When the state is false, it will show the local image. When the state is true, it will show the real image. The key thing that makes this work is the onLoad={} function in Image component. It runs when the image loading is done. So when the online image from URL is loaded, it will set the state to true and it will show the main image. This is how we can use React Native to show default source image while loading main image.

Contents in this project React Native Display Default Source Image While Loading Main Image :-

1. First of all we have to setup a local resource image in our react native project. I’m using the default thumbnail image. You can download the image from below If you want to use the same image.

2. Now make a images folder in your react native project.

3. Now paste the downloaded thumbnail image into images folder.

4. Open your project’s main App.js file and import useState, View, StyleSheet, Image and Text component.

5. Creating our main App component.

6. Creating a State named as onLoadImage with State update method setLoadImage with default value False.

7. Creating a function named as imageLoading(). In this function we would simply update the State value.

8. Creating our main Image component in return block.

Explanation :- Here when onLoadImage value is False then it will load the local resource image and when the State value is True then it load the original image. onLoad={} function calls when image load successfully from network.

9. Creating Style.

10. Complete Source Code for App.js File :-

Screenshots :-

 

No comments:

Post a Comment