In this article, we learn about React-native pagination example – infinity list, to explain this we use react-native Flatlist component in which we will render data in the form of pages or offset and limit etc, to do this
I have reacted API for pagination and will write a different post for APIs, in this example we will going to call that API call which returns infinite list so let’s start,
Import following component
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,ActivityIndicator,FlatList,TouchableOpacity,Alert} from 'react-native';
Write a constructor like below
constructor() { super(); this.state = { isLoading: true, responseList: [], fetchingStatus: false, setOnLoad : false, } this.page = 0; let onEndReached = false; }
See above constructor, we define state variable this like isLoading which indicate fetch API call is calling, responseList which type array which store fetch call response list, fetchingStatus only indicates for onLoadMore call fetching, this.page = 0 is the default value of the page which we want to fetch during the 1st API call
Create a method for API call
While creating a function, it’s good to create arrow function in this situation because we have to call the same function multiple times and arrow function does not create every render, so it’s good to use arrow function like below
apiCall =()=> { var that = this; that.page = that.page + 1; }
define a variable that and use that variable inside this method, also at the beginning of function I am adding page + 1 so that on the second API call it will get second (i.e. previous page count + 1)
after that call our standard fetch method like below:
If you want to learn more about Fetch API call then I request you to read our Post related Fetch GET API call
Fetch Get API call:
apiCall =()=> { var that = this; that.page = that.page + 1; console.log(" *********** call "+this.page); that.setState({ fetchingStatus: true }); fetch('https://techup.co.in/paginationList.php?page=' + that.page) .then((response) => response.json()) .then((responseJson) => { that.setState({ responseList: [ ...this.state.responseList, ...responseJson ], isLoading: false,setOnLoad: true }); }) .catch((error) => { console.error(error); that.setState({setOnLoad: false,fetchingStatus: false ,}); }); }
after success, response save response list in state variable responseList we are not saving new data each time
we are adding a new response in previously saved list, after that setting setOnLoad: true which means that we can call next API onLoadMore, the question is how to load data onLoadmore to do this Flatlist has inbuild properties like onEndReached which call when list reach ends, let’s understand using code see below:
Render data using FlatList
render() { return ( <View style = { styles.MainContainer }> { ( this.state.isLoading ) ? ( <ActivityIndicator size = "large" /> ) : ( <FlatList style={{width: '100%'}} keyExtractor = {( item, index ) => index } data = { this.state.reviewResponseList } ItemSeparatorComponent = {this.ItemSeparator} onScrollEndDrag={() => console.log(" *********end")} onScrollBeginDrag={() => console.log(" *******start")} initialNumToRender={8} maxToRenderPerBatch={2} onEndReachedThreshold={0.1} onMomentumScrollBegin = {() => {this.onEndReached = false;}} onEndReached = {() => { if (!this.onEndReached) { this.apiCall(); // on end reached this.onEndReached = true; } } } renderItem = {({ item, index }) => <View> <TouchableOpacity activeOpacity = { 0.7 } onPress = { this.onClick.bind(this,item) } > <View style = {styles.viewStyle}> <Text style = { styles.flatListItems }> { item.value } </Text> </View> </TouchableOpacity> </View> } ListFooterComponent = { this.BottomView } /> ) } </View> ); } }
In about code, I use FlatList to render data and I added one property called onEndReached which called when all rows have been rendered and the FlatList has been scrolled to within onEndReachedThreshold of the bottom.
Value 0.5 for onEndReachedThreshold means, when the FlatLast row item is reached within half of a screen-full of items from being visible
I added one property ListFooterComponent which show Footer view on FlatList we will display loader in this section let’s create a loader
BottomView =()=> { return ( <View> { ( this.state.fetchingStatus ) ? <ActivityIndicator size="large" color = "#F44336" style = {{ marginLeft: 6 }} /> : null } </View> ) }
This is display loader when onLoadmore API call is fetching data
Here is the full code
My App.js
You can also create another js file for this, I have added whole code in App.js
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow * @lint-ignore-every XPLATJSCOPYRIGHT1 */ import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,ActivityIndicator,FlatList,TouchableOpacity,Alert} from 'react-native'; export default class App extends Component<Props> { constructor() { super(); this.state = { isLoading: true, responseList: [], fetchingStatus: false, setOnLoad : false, } this.page = 0; let onEndReached = false; } componentDidMount() { // this.page = this.page + 1; this.apiCall(); } apiCall =()=> { var that = this; that.page = that.page + 1; console.log(" *********** call "+this.page); that.setState({ fetching_Status: true }); fetch('https://techup.co.in/paginationList.php?page=' + that.page) .then((response) => response.json()) .then((responseJson) => { that.setState({ reviewResponseList: [ ...this.state.reviewResponseList, ...responseJson ], isLoading: false,setOnLoad: true }); }) .catch((error) => { console.error(error); that.setState({setOnLoad: false, fetching_Status: false }); }); } onClick(item){ Alert.alert(item.value); // console.log(item); } ItemSeparator =()=> { return ( <View style={{ height: .5, width: "100%", backgroundColor: "#607D8B", }} /> ); } BottomView=()=> { return ( <View> { ( this.state.fetchingStatus ) ? <ActivityIndicator size="large" color = "#F44336" style = {{ marginLeft: 6 }} /> : null } </View> ) } render() { return ( <View style = { styles.MainContainer }> { ( this.state.isLoading ) ? ( <ActivityIndicator size = "large" /> ) : ( <FlatList style={{width: '100%'}} keyExtractor = {( item, index ) => index } data = { this.state.responseList } ItemSeparatorComponent = {this.ItemSeparator} onScrollEndDrag={() => console.log(" *********end")} onScrollBeginDrag={() => console.log(" *******start")} initialNumToRender={8} maxToRenderPerBatch={1} onEndReachedThreshold={0.1} onMomentumScrollBegin = {() => {this.onEndReached = false;}} onEndReached = {() => { if (!this.onEndReached) { this.apiCall(); // on End reached this.onEndReached = true; } } } renderItem = {({ item, index }) => <View> <TouchableOpacity activeOpacity = { 0.7 } onPress = { this.onClick.bind(this,item) } > <View style = {styles.viewStyle}> <Text style = { styles.flatListItems }> { item.value } </Text> </View> </TouchableOpacity> </View> } ListFooterComponent = { this.BottomView } /> ) } </View> ); } } const styles = StyleSheet.create( { MainContainer: { flex: 1, justifyContent: 'center', margin: 5, paddingTop: ( Platform.OS === 'ios' ) ? 20 : 0 }, footerStyle: { padding: 7, alignItems: 'center', justifyContent: 'center', borderTopWidth: 2, borderTopColor: '#009688' }, viewStyle: { padding: 7, height: 70, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F44336', borderRadius: 5, margin: 5 }, flatListItems: { fontSize: 20, color: '#fff', padding: 10, } });
Thank you 🙂
I have been reading out some of your stories and it’s clever stuff. I will make sure to bookmark your website.
Thanks a lot 🙂
You can also subscribe via email