Quick Summary

React Native FlatList is a component in the React Native framework used to render large data lists. It can efficiently render only the visible items on the screen, conserving memory and improving performance. The FlatList component also provides scrolling, pull-to-refresh, and item selection features. It is highly customizable and can be used to create a variety of list-based UIs in React Native applications. With FlatList, developers can easily manage and display large data sets in a performant and user-friendly way. In React Native, we have two ways to render a bunch of data: FlatList and the map function of Javascript.

Table of Contents

Introduction to FlatList

React Native FlatList is a powerful component in React Native that enables developers to display large data lists efficiently. It is a high-performance and flexible way to render content in a scrollable view, essential for mobile apps that display many items in a limited space. With FlatList React Native, developers can easily create scrollable lists responsive to user input and display only the items currently visible on the screen, reducing the memory and processing power needed to render the list.

Additionally, FlatList React Native provides several features that make it easy to add animations, handle user inputs, and customize the rendering of individual list items. If you’re looking to build performant, responsive, and dynamic mobile apps with React Native, FlatList is an essential tool in your toolkit.

What is React Native FlatList?

FlatList is a component in React Native that efficiently renders large lists by only rendering the items currently visible on the screen. This is beneficial in mobile applications where scrolling through long data lists is a common user experience. FlatList React Native supports horizontal scrolling, column layouts, and dynamic resizing. With FlatList in React Native, developers can create performant and responsive applications that handle large amounts of data without sacrificing user experience.

After understanding what is FlatList in React Native, let’s look at the basic structure of FlatList.

Understand FlatList Essential: The Core Structure

A React Native FlatList is a component that displays a scrolling list of data, usually with multiple rows of items. The basic structure includes:

Copy Text
<FlatList data={} renderItem={} keyExtractor={item => item.id} />

This is just a brief overview, and there are many variations and options for customizing a FlatList React Native. There are some primary and optional React Native props that you can pass into a FlatList to render some items that meet your desired result.

Primary Props

There are three required Primary Props in the FlatList. Let’s go through all the Primary Props and understand why we use them and why they are primary props.

  • data: It accepts the array of items you want to pass into the FlatList.
  • renderItem: This told the FlatList how to render each item in the list, which has an index for every item. From that index, you can add conditions.
  • keyExtractor: This prop extracts the unique key for a given item, which should be a string.

With the primary properties, FlatList is ready to render all the items on the screen. Now, we will go through the optional properties.

Optional Props

There is a prominent question: “What is extra data in FlatList?” To simplify the understanding of the extra data. They are the non-required props available in the FlatList for rendering list items. Below, we have used some non-required props for the FlatList.

Scale-Up Your User’s Experience With React Native FlatList And Its Props

Elevate your user experience. Hire React Native Developers from Bacancy and optimize your React Native app by choosing FlatList for rendering similar data, avoiding needing map functions or loops.


FlatList Syntax (Sample Usage)

How will you use FlatList to show data in React Native? Below is an example of rendering data in a FlatList in a React Native Project.

Example #1

Copy Text
import React from ‘react’;
import { Text, View, StyleSheet, FlatList } from 'react-native';

// Component to render individual item
const Item = ({name}) => {
  return(
    <View style={styles.item}>
      <Text style={{color: 'white'}}>{name}</Text>
    </View>
  );
}

export default function App() {
  // An array of countries to render
  const countries = [
    {
      id: '1',
      name: 'India',
    },
    {
      id: '2',
      name: 'USA',
    },
    {
      id: '3',
      name: 'UK',
    },
    {
      id: '4',
      name: 'China',
    },
    {
      id: '5',
      name: 'Nigeria',
    },
    {
      id: '6',
      name: 'Uganda',
    },
  ];

  // Component to render items
  const renderItem = ({item}) => (
    <Item name={item.name} />
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={countries}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginTop: 10,
    padding: 10,
  },
  item: {
    backgroundColor: 'red',
    padding: 10,
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 8,
  },
});

The output will look like this:

FlatList Syntax

How FlatList React Native Work?

React Native ScrollView gives you the option to customize your list, but it means that all the items have to be loaded every time, which can lead to slower UI/UX. With React Native FlatList, items are loaded only if visible and deleted when off the screen, making it ideal for large data sets. Additionally, scrolling is provided by default. List data can be scrolled without using additional components like ScrollView. There are also the following features available with FlatList:

  • Header section
  • Footer section
  • Horizontal scrolling
  • Separator
  • Pull to refresh
  • Scroll loading
  • Scroll to a specific position in the list
  • Multiple column support

The scrollable elements in Flat List in React Native are rendered by the ScrollView component under the hood. In contrast to the usual ScrollView, FlatList efficiently renders data by loading it only when necessary, thus consuming less memory and processing time. Let’s start with the primary procedure for displaying list data in a React Native FlatList example with the help of the map function.

Displaying a List in React Native with Map

The JavaScript map method can go through an array containing information, calculate each item, and present it in a React Native application. Rather than the for loop or the forEach method, you can use the map method to iterate through an array and create a modified array. This way, returning a new array with the changes is simple. Let’s look at an example of a table with personal data containing Names and Phone Numbers:

Copy Text
const users = [
  {
	id: "1",
	name: "John Green",
            phone: “9876543210”,
  },
  {
	id: "2",
	name: "Ranson Kons",
            phone: “6876553210”,
  },
  {
	id: "3",
	name: "Remity Sons",
            phone: “6376943210”,
  },
  {
	id: "4",
	name: "Randy Samsun",
            phone: “6473823910”,
  },
  {
	id: "5",
	name: "Rose Cane",
            phone: “6352938476”,
  },
  {
	id: "6",
	name: "Zimmy Jang",
            phone: “7264029008”,
  },
  {
	id: "7",
	name: "Jessieca Johnson",
            phone: “4539287263”,
  },
  {
	id: "8",
	name: "Julian Gulgowski",
            phone: “4234234343”,
  },
  {
	id: "9",
	name: "Ellen Veum",
            phone: “6543987253”,
  },
  {
	id: "10",
	name: "Lorena Rice",
            phone: “6321936476”,
  },
];

Now to render all data on the app screen, you can loop through it and wrap it in a UI component using the below code:

Copy Text
export default function App() {
  return (
    <View style={styles.container}>
      {users.map((user) => {
        return (
          <View>
            <Text style={styles.item}>{user.name}</Text>
            <Text style={styles.item}>{user.phone}</Text>
          </View>
        );
      })}
    </View>
  );
}

//styles to see the data more clearly

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 50,
  },
  item: {
    padding: 20,
    fontSize: 15,
    marginTop: 5,
  }
});

When you execute the code on your machine or in the Snack, you can view a list of data which appears on the display on the left. Nevertheless, you can’t see all the information since it’s not scrollable. To make a rollable data collection, you must embed the View component inside the ScrollView component.

Note: ScrollView requires a parent element with a predetermined height.

The ScrollView is a React Native container designed for scrolling, allowing vertical and horizontal movement. Unless specified otherwise, the default orientation of its children is vertical column formation. The horizontal prop must be set to true to cause these elements to appear in a single row.

Copy Text
<ScrollView horizontal=”true”>

For this example, we will stick with the default setting so our information is arranged vertically in a single column.

Copy Text
import * as React from 'react';
import { Text, View, StyleSheet, ScrollView } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <ScrollView>
        <View>
          {users.map((user) => {
            return (
              <View>
                <Text style={styles.item}>{user.name}</Text>
                <Text style={styles.item}>{user.phone}</Text>
              </View>
            );
          })}
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 50,
    flex: 1,
  },
  item: {
    padding: 20,
    fontSize: 15,
    marginTop: 5,
  }
});

Customizing the Mapped List

If you’re looking to create a more personalized list view, with modifications like added design, updated item features, and gesture-based pagination, you’ll need to add these elements yourself. The map method for listing data in React Native is quite versatile; it allows you to configure the list view according to your needs.

Likewise, you can configure a ScrollView to flip through the views with just a swipe if you activate the pagingEnabled prop. On iOS devices, you can set up two props, maximumZoomScale, and minimumZoomScale, allowing users to zoom in and out of a ScrollView containing a single item.

Creating a React Native list for displaying data is not as straightforward as one would think. Adding features to your list display requires additional coding, and if handling large amounts of data, ScrollView isn’t the best solution. That’s because the map method with ScrollView loads all data to render every time the component renders, which can slow down performance. For this reason, extra work may be needed to handle infinite data using a pagination method.

Fortunately, there is an easier way: FlatList component. This component simplifies listing infinite numbers of data while optimizing the app’s performance.

Displaying a List with a React Native FlatList

The FlatList component necessitates using two properties: data and renderItem. The data property accepts an array of data to be displayed. In contrast, the renderItem property specifies a function that takes this data as input and returns a formatted component for presentation on the screen.

The fundamental code for implementing a FlatList to display a list of person data is shown below:

Copy Text
<FlatList
 data={users}
 renderItem={({item}) => (<>
<Text>{item.name}</Text>
<Text>{item.phone}</Text>
</>)}
/>

When you execute the application using the provided code, you may encounter a warning prompting you to include unique keys for each list item. To address this concern, you should initially select a specific data attribute, such as ID or email address, and then define it using the keyExtractor property within the FlatList component.

The essential code for utilizing React Native FlatList example with keyExtractor, data, and renderItem would resemble this:

Copy Text
import React from "react";

import { SafeAreaView, FlatList, StyleSheet, Text, View } from "react-native";

const persons = [ /* list of person data from earlier */ ];

export default function App() {

  return (
    <SafeAreaView style={styles.container}>
      <FlatList 
        data={users}
        renderItem={({ item }) => <Text                       style={styles.item}>{item.name}</Text>}
        keyExtractor={(item) => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 50,
    flex: 1,
  },
  item: {
    padding: 20,
    fontSize: 15,
    marginTop: 5,
  }
});

FlatList Separator

The ItemSeparatorComponent property in FlatList inserts a separator between every item within the list.

Copy Text
const myItemSeparator = () => {
  return (
    <View
     style={{ height: 1, backgroundColor: "gray", marginHorizontal:10 }}
    />
  );
};

FlatList Empty List Component

There may be occasions when you receive an empty list without any data. In such instances, displaying a blank screen. Consequently, the React Native FlatList example includes a distinct ListEmptyComponent property, which accepts a component and displays it when the data list is empty.

Copy Text
const myListEmpty = () => {
  return (
    <View style={{ alignItems:"center" }}>
    <Text style={styles.item}>No data found</Text>
    </View>
  );
};

The FlatList component additionally offers support for header and footer components. You wish to include a component such as a search bar, you can utilize the ListHeaderComponent property. Likewise, for the end list loading component, you can employ the ListFooterComponent property within the FlatList. The fundamental code for an inline header component prop is demonstrated as follows:

Copy Text
<FlatList
   data={users}
   renderItem={({item}) => (<><Text>{item.name}</Text>
<Text>{item.phone}</Text></>)}
   ListHeaderComponent={() => (
      <Text style={{ fontSize: 30, textAlign: "center",marginTop:20,fontWeight:'bold',textDecorationLine: 'underline' }}>
      List of Persons
      </Text>
  )}
/>

And with the footer component prop added:

Copy Text
<FlatList
   data={users}
   renderItem={({item}) => (<><Text>{item.name}</Text>
<Text>{item.phone}</Text></>)}
   ListHeaderComponent={() => (
      <Text style={{ fontSize: 30, textAlign: "center",marginTop:20,fontWeight:'bold',textDecorationLine: 'underline' }}>
      List of Users
      </Text>
  )}
  ListFooterComponent={() => (
      <Text style={{ fontSize: 30, textAlign: "center",marginBottom:20,fontWeight:'bold' }}>Thank You</Text>
  )}
/>

Now put it all together and it will look like this:

Copy Text
import React from "react";
import { SafeAreaView, FlatList, StyleSheet, Text, View } from "react-native";

const persons = [
/* List of person data from earlier */
];

export default function App() {

  const myItemSeparator = () => {
    return <View style={{ height: 1, backgroundColor: "gray",marginHorizontal:10}} />;
    };
  
  const myListEmpty = () => {
    return (
      <View style={{ alignItems: "center" }}>
      <Text style={styles.item}>No data found</Text>
      </View>
    );
  };
  
return (
  <SafeAreaView style={styles.container}>
    <FlatList
      data={users}
      renderItem={({ item }) => (<><Text style={styles.item}>{item.name}</Text>
<Text style={styles.item}>{item.phone}</Text></>)}
      keyExtractor={(item) => item.id}
      ItemSeparatorComponent={myItemSeparator}
      ListEmptyComponent={myListEmpty}
      ListHeaderComponent={() => (
        <Text style={{ fontSize: 30, textAlign: "center",marginTop:20,fontWeight:'bold',textDecorationLine: 'underline' }}>
          List of Users
        </Text>
      )}
      ListFooterComponent={() => (
        <Text style={{ fontSize: 30, textAlign: "center",marginBottom:20,fontWeight:'bold' }}>Thank You</Text>
      )}
    />
  </SafeAreaView>
  );
 }
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 5,
    fontSize: 30,
  },
  item: {
    padding: 20,
    marginTop: 5,
    fontSize: 15,
  },
});

Now put it all together, and it will look like this:

Header and Footer Components

Utilizing methods like a map or other looping mechanisms to display data may offer flexibility for customizing the list to your preferences. However, as the volume of data increases, it becomes crucial to exercise caution regarding the large amount of data being rendered on the visible screen.

React Native FlatList makes it easy to work with many items, making it a great choice for managing lengthy data sets. Its built-in lazy loading system takes the burden off you, so you can just let FlatList do its job. To learn more about this component, check out the Expo or React Native documentation.

Conclusion

Summing up this blog post on React Native FlatList, we can infer that FlatList in React Native is an amazing component for delivering an unmatchable user experience. If you are a developer and want to use an infinite scrolling list, you should use FlatList React Native. Also, make sure to take into consideration the best practices that can take your user’s experience to the next level. However, being a business owner, if you are still confused about the benefits and functionalities that you can introduce in your existing React Native application or implement the same into your next project, partner with a React Native App Development Company like Bacancy to help you gain more insight and make the right choice.

Frequently Asked Questions (FAQs)

FlatList is a React Native component that renders massive lists of data efficiently. It optimizes performance by displaying only the visible items on the screen, saving memory and enhancing scrolling smoothness.

Yes, You can use React Native FlatList inside the ScrollView, but you will face a warning related to the “VirtulizedList never nested”.

When we use FlatList inside ScrollView in React Native, then it will throw a warning “VirtualizedLists should never be nested inside plain ScrollViews with the same orientation”. So, we have to use FlatList outside ScrollView, and along with it, we have to pass a prop “ListHeaderComponent” to render components that you want to render before FlatList and use “ListFooterComponent” to render components that you want to render after FlatList.

Experience the Next Gen App Performance with FlatList

Future Proof your App against performance hustles in the future with Bacancy and stand ahead of your competitors.

Book A Free Consultation

Build Your Agile Team

Hire Skilled Developer From Us

solutions@bacancy.com

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?