Search code examples
reactjsreact-nativeinfinite-scrollreact-native-flatlist

Infinite scroll FlatList headers


In my react native app I use 2 endpoints of cocktailDB API: https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list - drink categories https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Ordinary%20Drink - drinks list

I made a FlatList that onEndReached() changes the page number and makes an API call to get drinks for a subsequent category. The drinks get added to the drinksList array so that the data from the previous API call remains on top.

       <FlatList
          keyExtractor={(item) => item.idDrink.toString()}
          data={drinksList}
          onEndReached={() => {
            if (!isLoading) {
              setCurrentPage((page) => page + 1);
            }
          }}
          onEndReachedThreshold={0.3}
          renderItem={({item}) => {
            return (
              <View>
                <Image
                  style={{height: 100, width: 100, marginRight: 20}}
                  source={{uri: item.strDrinkThumb}}
                />
                <Text>{item.strDrink}</Text>
              </View>
            );
          }}
        />

I assigned array index as an id to each category item, so that I can get access to them based on the currentPage value.

My question is, how do I add a header to each drink category when it gets rendered after an API call. I tried doing it with ListHeaderComponent prop of FlatList but it didn't work cause there is only one FlatList, so the header changes but remains on the very top of the FlatList but I need that category name to be on top of each FlatList "page"


Solution

  • You have to use SectionList instead of FlatList which has multiple sections like you can say multiple headers.

    https://reactnative.dev/docs/sectionlist