Create a Custom Loader in React Native

In a mobile app, we often fetch data from a web-service/API. And an app takes time to fetch this data and render it on the screen. In such cases, we want to render a loader on the screen indicating to the user that there is a process running in the background. Here is how you can add your own custom loader in react-native apps.

First things first, choosing a loader. Head over here and choose a loader that you like. Make sure you toggle the transparent background to yes, and have the file format selected as .gif. Download the file and copy it to /src/assets.

Next, we must add animated gif support to our app. To do this, open android/appp/build.gradle and add the following line to your dependencies block:

compile 'com.facebook.fresco:animated-gif:1.10.0'

Next, create a file PreLoader.js in /src/components/ and add the following code to the file:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image} from 'react-native';
export default class PreLoader extends Component {
_renderLoader = () => {
if (this.props.preLoaderVisible) return (
<View style={styles.background}>
<Image source={require('../assets/preLoader.gif')} />
</View>
)
else return null;
}
render () {
return (
this._renderLoader()
)
}
}
const styles = StyleSheet.create ({
background: {
backgroundColor: <ENTER_BACKGROUND_COLOR_HERE>,
flex: 1,
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
alignItems: 'center',
justifyContent: 'center'
}
});

Enter your choice of background color where mentioned. You also choose a partially or completely transparent background if you want.

Next, open the file where you want the loader to appear. Add an import statement as follows: (assuming your current file is in a separate directory in /src)

import PreLoader from '../components/PreLoader';

Include a state variable named loading and set it to true. Make sure to set loading to false on componentDidMount() which is the method called when the screen is rendered. Just before making any fetch call to an API, set the loading to true, and set it to false inside the componentDidReceiveProps() method.

Add the following line in your render() method:

<PreLoader preLoaderVisible={this.state.loading} />

And you’re done! Open up your app, and you should see your own custom loader when you make an API call.

Written by

I’m a undergrad at BITS Pilani, Goa Campus, expecting to graduate in 2022. I love coding and writing about technical stuff.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store