To create an infinite loading list in React Native, we need to follow few steps –
- Create a loader at the footer of the list which can indicate that new records are fetching.
- An event to trigger when end of the list is reached. It will indicate to start fetching records.
- Populate new records in the list.
In our list footer article we saw how to add a footer to a flatlist. We can use that to add a loader and load more button.
To invoke a trigger, we can use onEndReached
prop. It runs a function when the end of the list is reached. We can make a server request in it. Also, we can add some threshold using onEndReachedThreshold
prop by providing a numerical value.
After getting the new data, we can append them to our data variable and request a re-render.
Code Example
import React, { useState } from "react"; import { FlatList, SafeAreaView, StyleSheet, Text, View, StatusBar, ActivityIndicator, TouchableOpacity } from "react-native"; let SUPERHERO_DATA = [ { id: '1', title: 'Ironman', }, { id: '2', title: 'Thor', }, { id: '3', title: 'Captain America', }, { id: '4', title: 'Hulk', }, { id: '5', title: 'Hawkeye', }, { id: '6', title: 'Spiderman', }, { id: '7', title: 'Antman', }, { id: '8', title: 'Black Widow', }, { id: '9', title: 'Scarlett Witch', }, { id: '10', title: 'Vision', }, { id: '11', title: 'Falcon', }, ]; const App = () => { const [isRefreshing, setIsRefreshing] = React.useState(false); const [isMoreItems, setIsMoreItems] = React.useState(true); const [toReRenderList, setToReRenderList] = React.useState(1); const renderItem = ({ item, index, separators }) => ( <View style={styles.item}> <Text>{item.title}</Text> </View> ) const footerView = () => { if(isRefreshing) { return ( <View style={{height: 60}}> <ActivityIndicator /> </View> ) } else { if(isMoreItems) { return ( <TouchableOpacity style={{height: 60}} onPress={() => { setIsRefreshing(true) fetchNewData() } }> <Text style={{textAlign: 'center'}}>Load More</Text> </TouchableOpacity> ) } else { return null } } } const fetchNewData = (info) => { if(isMoreItems && !isRefreshing) { setIsRefreshing(true) // Make a api call here to fetch data // We are randomly putting some data here // and provide timeout setTimeout(() => { SUPERHERO_DATA = SUPERHERO_DATA.concat([{ id: '12', title: 'Superman', }, { id: '13', title: 'Batman', }, { id: '14', title: 'Flash', }, { id: '15', title: 'Cyborg', },]) setIsRefreshing(false) setIsMoreItems(false) setToReRenderList(toReRenderList + 1) }, 5000) } } return ( <SafeAreaView style={styles.container}> <FlatList data={SUPERHERO_DATA} renderItem={renderItem} onEndReached={fetchNewData} onEndReachedThreshold={0.01} ListFooterComponent={footerView} extraData={toReRenderList} /> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, marginTop: StatusBar.currentHeight || 0, }, item: { backgroundColor: '#fff000', padding: 20, marginVertical: 25, }, }); export default App;
The output will look like this –
In the above image, we have a list of superheroes and at the footer there is a circular loader. After fetch, new data will be appended to this list.
In the code we declared 3 state variables –
-
isRefreshing
– (Line no. 52) Used to indicate whether to show circular loader in the footer or not. -
isMoreItems
– (Line no. 53) It indicates whether there are more items to fetch from api or from local storage. If it is true then show Load More button or circular loader in footer. Otherwise keep the footer empty because there are no more items available. -
toReRenderList
– (Line no. 54) This value is used forextraData
prop because FlatList is a pure component. So we need to instruct it to re-render when our data changes. This prop is used for that purpose.
Next we declared footerView()
function which creates view for circular loader, loading button and for null.
To accomplish the infinite loading, we are using 3 props of FlatList –
-
onEndReached
– To run a function when end of list is within threshold. -
onEndReachedThreshold
– To set a threshold for list. If set to 0 then there will not be auto fetching of new items. A Load More button will show. But if set to >0 then circular loader will render andonEndReached
function will call as soon as the end of list is within this threshold value. Value lies from 0 to 1+. 0.25 means that the function will call when 75% of list is scrolled. -
ListFooterComponent
– For rendering circular loader and Load More button.
Live Demo
Conclusion
In this article we saw how FlatList can easily render an infinite list in React Native. With very few lines of code, we can implement a fully working infinite loading.
Read These Next ⬇️
How to Create a Simple List?
How to Select Single Item from List?
How to Select Multiple Items from List?
How to add Separator between list items?
How to create Multiple columns List?
How to Create Placeholder Message in Empty List?
How to Add Footer to the List?
How to Add Header to the List?
How to create Horizontal List?
How to create Inverted List?
How to create Pull to Refresh in List?
How to create Infinite Loading List?
How to create Section List?
React Native Series
Alert
- Basic Alert
- Dismiss on Clicking Outside
- Input Fields in Alert Dialog – Prompt()
- Dark-Light Theme of Dialog
ActivityIndicator
- Basic Circular Loader
- Change size of Circular Loader
- Show/hide Circular Loader
- Change color of Circular Loader
Button
FlatList
- Simple List
- Single Item Selection from List
- Multiple Item Selection from List
- Adding separator between list items
- Multiple columns List
- Showing Message in Empty List
- Add Footer to the List
- Add Header to the List
- Horizontal List
- Inverted List
- Pull to Refresh in List
- Infinite Loading List
SectionList
ScrollView
- ScrollView
- Stick Single Item at Header
- Stick Multiple Items at Header
- Stick Item at Footer
- Hide Sticky Element on Scroll
Image
- Display Image from remote url
- Display local storage image
- Display Base64 Image
- Display Gif & Webp Images
- Adding Blur to Image
- Displaying loader for Image
- Resizemode for Images
- Setting Default Placeholder Image
- Background Image
Modal
RefreshControl
- RefreshControl
- Change Refresh Loader Color
- Change Refresh Loader Size
- Change Refresh Loader Background Color
- Title under Refresh Loader
- Change color of title under refresh loader
StatusBar
- Get StatusBar Size
- Change StatusBar Background Color
- Display StatusBar icons & text in While Color
- Display StatusBar icons & text in Dark Color
- Hiding StatusBar
- Translucent StatusBar
Switch
Text
- Adding Text
- Bold Text
- Italic Text
- Underline Text
- Selecting Text for copy-paste
- Changing Highlight Color of Text Selection
- Fit text in View box
- Clickable anchors in text
- Truncate Lengthy Text
TextInput
- Simple Input Field
- Auto Capitalize Text in Input Field
- Multiline Input Field
- Hide Cursor in Input Field
- Clear input Field using X
- Clear input Field when focused
- Change Cursor Color in Input Field
- Disable input field
- Icon at the left of Input Field
- Dark-Light Keyboard
- Avoid Overlapping of Keyboard
- Limiting Characters in Input Field
- Numeric Keyboard
- Email Id Keyboard
- Phone number Keyboard
- Url Keyboard
- Placeholder in input field
- Placeholder Color in Input Field
- Password Input Field
- Programmatically select text in Input Field
- Change Text Selection Color in Input Field
- Select Whole text in Input Field on Focus
- Write text from center in input field
- Changing underline color of input field
TouchableWithoutFeedback
TouchableHighlight
TouchableOpacity
Pressable
Appearance
AppState
ToastAndroid
Dimensions
Keyboard