Paging in ListView
This is an Example of Infinite Loading Listview in React Native using FlatList. A React Native list view that supports infinite scroll. In mobile application development, ListView has a very important part as we use ListView in almost all applications. If we have to load a huge amount of data in a listview we have to use pagination for the seamless performance. A ListView with Load More Button in the bottom to load data can be an option but what if we load the data automatically when the user reaches the end of the list? This feature will give a good user experience to your application users.
What is pagination?
Let’s take a case where you can simply imagine what if Facebook loads all the Facebook posts from the Facebook database on your Facebook wall? Doesn’t it sound nasty? It will take hundreds of hours even more than that so what is the best way to load the data? Simply paging. When you open the Facebook they just show you 10-20 post and while you scroll the Facebook they load the next 10-20 posts in background. That is what the paging is.
In our example,
- We are loading the first 10 posts from the web API call in componentDidMount.
- While the user reaches the bottom of the list we call the Web API again to get the next 10 posts.
We are using a variable offset to manage the index on upcoming Data. We will increase the offset by 1 after the successful call of the web API so that when we call the web API next time we will get the next data-set. So let’s get started with the example.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Code for Infinite Loading Listview
Now Open App.js in any code editor and replace the code with the following code
App.js
// Example of Infinite Loading Listview in React Native using FlatList
// https://aboutreact.com/infinite-list-view/
// import React in our code
import React, {useState, useEffect} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
View,
Text,
StyleSheet,
FlatList,
ActivityIndicator,
} from 'react-native';
const App = () => {
const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState([]);
const [offset, setOffset] = useState(1);
const [isListEnd, setIsListEnd] = useState(false);
useEffect(() => getData(), []);
const getData = () => {
console.log(offset);
if (!loading && !isListEnd) {
console.log('getData');
setLoading(true);
// Service to get the data from the server to render
fetch('https://abooutreactapis.000webhostapp.com/getpost.php?offset='
+ offset)
// Sending the currect offset with get request
.then((response) => response.json())
.then((responseJson) => {
// Successful response from the API Call
console.log(responseJson);
if (responseJson.results.length > 0) {
setOffset(offset + 1);
// After the response increasing the offset
setDataSource([...dataSource, ...responseJson.results]);
setLoading(false);
} else {
setIsListEnd(true);
setLoading(false);
}
})
.catch((error) => {
console.error(error);
});
}
};
const renderFooter = () => {
return (
// Footer View with Loader
<View style={styles.footer}>
{loading ? (
<ActivityIndicator
color="black"
style={{margin: 15}} />
) : null}
</View>
);
};
const ItemView = ({item}) => {
return (
// Flat List Item
<Text
style={styles.itemStyle}
onPress={() => getItem(item)}>
{item.id}
{'.'}
{item.title.toUpperCase()}
</Text>
);
};
const ItemSeparatorView = () => {
return (
// Flat List Item Separator
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
};
const getItem = (item) => {
// Function for click on an item
alert('Id : ' + item.id + ' Title : ' + item.title);
};
return (
<SafeAreaView style={{flex: 1}}>
<FlatList
data={dataSource}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={ItemSeparatorView}
renderItem={ItemView}
ListFooterComponent={renderFooter}
onEndReached={getData}
onEndReachedThreshold={0.5}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
padding: 10,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Output in Online Emulator
That was the example of Infinite Loading Listview in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Hey! The tutorial is quite useful. I will also recommend to check out a library named react-native-paginatable-list. Here is the link. https://www.npmjs.com/package/@twotalltotems/paginatable-list
It saves your time in implementing the pull-to-refresh and reach list end to load more items.
Hey Hi,
Thanks to suggesting the library 🙂 I’ll surely make an example with the help of it and will share with you. Thank you again for the suggestion.
What if we have to do Multiple Async Api calls? we need to call the Api againg in loadmore?
Sorry, I am not clear. Can you please share more details? You can call it in loadMoreData method after the success of fetch(‘https://aboutreact.herokuapp.com/getpost.php?offset=’ + this.offset)
Thank you, Sir. Very concise and precise. Just saved my day!
If it is a post method, how to handle it?