How to create infinite loading list in React Native? Code Example

Table of Contents Hide
  1. Code Example
    1. Live Demo
  2. Conclusion

To create an infinite loading list in React Native, we need to follow few steps –

  1. Create a loader at the footer of the list which can indicate that new records are fetching.
  2. An event to trigger when end of the list is reached. It will indicate to start fetching records.
  3. 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 –

adding infinite loading in flatlist in react native

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 –

  1. isRefreshing – (Line no. 52) Used to indicate whether to show circular loader in the footer or not.
  2. 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.
  3. toReRenderList – (Line no. 54) This value is used for extraData 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 –

  1. onEndReached – To run a function when end of list is within threshold.
  2. 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 and onEndReached 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.
  3. ListFooterComponent – For rendering circular loader and Load More button.

Live Demo

Open 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.


React Native Series

Alert

  1. Basic Alert
  2. Dismiss on Clicking Outside
  3. Input Fields in Alert Dialog – Prompt()
  4. Dark-Light Theme of Dialog

ActivityIndicator

  1. Basic Circular Loader
  2. Change size of Circular Loader
  3. Show/hide Circular Loader
  4. Change color of Circular Loader

Button

  1. Simple Button
  2. Change Button Color
  3. Disable Button Click
  4. Disable touch sound on Button click

FlatList

  1. Simple List
  2. Single Item Selection from List
  3. Multiple Item Selection from List
  4. Adding separator between list items
  5. Multiple columns List
  6. Showing Message in Empty List
  7. Add Footer to the List
  8. Add Header to the List
  9. Horizontal List
  10. Inverted List
  11. Pull to Refresh in List
  12. Infinite Loading List

SectionList

  1. Section List

ScrollView

  1. ScrollView
  2. Stick Single Item at Header
  3. Stick Multiple Items at Header
  4. Stick Item at Footer
  5. Hide Sticky Element on Scroll

Image

  1. Display Image from remote url
  2. Display local storage image
  3. Display Base64 Image
  4. Display Gif & Webp Images
  5. Adding Blur to Image
  6. Displaying loader for Image
  7. Resizemode for Images
  8. Setting Default Placeholder Image
  9. Background Image

Modal

  1. Basic Modal
  2. Slide from bottom Modal
  3. Fade In Modal
  4. Transparent Overlay Modal

RefreshControl

  1. RefreshControl
  2. Change Refresh Loader Color
  3. Change Refresh Loader Size
  4. Change Refresh Loader Background Color
  5. Title under Refresh Loader
  6. Change color of title under refresh loader

StatusBar

  1. Get StatusBar Size
  2. Change StatusBar Background Color
  3. Display StatusBar icons & text in While Color
  4. Display StatusBar icons & text in Dark Color
  5. Hiding StatusBar
  6. Translucent StatusBar

Switch

  1. Simple Switch
  2. Disable Switch
  3. Change Switch Colors

Text

  1. Adding Text
  2. Bold Text
  3. Italic Text
  4. Underline Text
  5. Selecting Text for copy-paste
  6. Changing Highlight Color of Text Selection
  7. Fit text in View box
  8. Clickable anchors in text
  9. Truncate Lengthy Text

TextInput

  1. Simple Input Field
  2. Auto Capitalize Text in Input Field
  3. Multiline Input Field
  4. Hide Cursor in Input Field
  5. Clear input Field using X
  6. Clear input Field when focused
  7. Change Cursor Color in Input Field
  8. Disable input field
  9. Icon at the left of Input Field
  10. Dark-Light Keyboard
  11. Avoid Overlapping of Keyboard
  12. Limiting Characters in Input Field
  13. Numeric Keyboard
  14. Email Id Keyboard
  15. Phone number Keyboard
  16. Url Keyboard
  17. Placeholder in input field
  18. Placeholder Color in Input Field
  19. Password Input Field
  20. Programmatically select text in Input Field
  21. Change Text Selection Color in Input Field
  22. Select Whole text in Input Field on Focus
  23. Write text from center in input field
  24. Changing underline color of input field

TouchableWithoutFeedback

  1. TouchableWithoutFeedback

TouchableHighlight

  1. TouchableHighlight

TouchableOpacity

  1. TouchableOpacity

Pressable

  1. Pressable
  2. Creating Ripple Effect

Appearance

  1. Dark-Light System Color Scheme

AppState

  1. AppState – Foreground/Background State of App

ToastAndroid

  1. Creating Android Toast Message

Dimensions

  1. Getting Screen & Window Dimensions

Keyboard

  1. Dismiss Keyboard Programmatically

👉 Learn Material Design using React Native Paper