FlatList in React Native

Learn via video courses
Topics Covered

Overview

Like other frameworks, React Native provides a way for iterating through a list of data. The ability to dynamically render a collection of data is a crucial aspect of software development, and flatlist react native provides us with this capability. FlatList can be helpful in various situations, such as showing a list of to-do tasks or rendering a list of products on e-commerce purchasing sites. The following tutorial will introduce you to the concept of FlatList in React Native and guide you on how to use it in your project.

Advantages of React Native FlatList

There are several advantages of using FlatList in your React native application:

High Performance: FlatList is designed for high performance. It can handle large datasets without any performance issues. It uses a virtual rendering mechanism that renders only the items that are currently visible on the screen, reducing the overall memory consumption.

Flexibility: FlatList is highly flexible. It allows developers to customize its appearance and functionality according to their requirements. It offers various props and features that make it highly adaptable.

Efficiency: FlatList is highly efficient and optimized for mobile devices. It is designed to consume less memory and use less CPU, which results in better performance.

Scalability: FlatList is highly scalable. It can handle large datasets without any issues. It is an ideal choice for applications that require a lot of data to be displayed, such as e-commerce applications, social media applications, and news applications.

Smooth Scrolling: FlatList provides smooth scrolling when dealing with large datasets. This makes the user experience more seamless and enjoyable.

React Native Flatlist Basic Structure

The structure of FlatList is straightforward and can be achieved with just one line of code, as shown in the following code snippet:

While this code is simple and effective for creating a basic FlatList, additional props can be passed to the FlatList to enhance its functionality. Props, short for properties, can be add-ons that enhance the functionality of a FlatList.

FlatList React Native allows primary and optional props to be passed to render items and achieve desired results.

Primary Props

The primary props consist of three key properties, including:

data: This property accepts an array of items to be passed to the FlatList.

renderItem: This property includes the individual items to be displayed, represented by (item, index, and separator). Each item has an index and a function that can be used to modify the item before rendering.

keyExtractor: This property is used to extract the unique key for a given item.

Using these primary props, a FlatList can render items on the screen.

Optional Props

Optional props are available for rendering a list item. These non-compulsory properties include the horizontal prop for horizontal scrolling, getItemLayout for optimizing the rendering performance, ListHeaderComponent and ListFooterComponent for adding header and footer views, and more.

Syntax of Flatlist

Create a react-native project using Expo, and copy the below command to your terminal.

Let’s take a simple example to understand FlatList structure and syntax properly. In this example, we will render the weak days on screen using FlatList. Copy the below code in App.js.

File-name: App.js

Output: output

Let's break the above code to understand the flatlist syntax. We are using the following Flatlist component:

The first prop is the data prop, which is specifying the array of weakdays that we want to render on screen the weakDays is an array of objects where each object contains two properties id and day. The renderWeakDays is a function that will be used to render each weakDay item in the FlatList. We have created a simple card component to hold weakday text using a View and Text component. Each item in the flatlist should have a unique id through which the flastList component can know the order of items in the list.

React Native Flatlist Features

FlatList React Native provides an efficient way to render a list of elements on mobile applications. Some of the key features that make a FlatList component highly flexible are:

Cross-platform compatibility: The FlatList component is fully cross-platform, which means it can be used to render flat lists on both iOS and Android devices with ease.

Configurable viewability callbacks: The FlatList component also allows developers to configure viewability callbacks, which can be useful in situations where performance is critical and you only want to render items that are currently visible on the screen.

Header, footer, and separator support: The FlatList component also supports header, footer, and separator items, which can be used to add additional content to the flat list as needed.

Optional horizontal mode: The FlatList component also supports a horizontal mode, which can be useful in certain situations where a horizontal layout is more suitable than a vertical one.

Scroll loading: The FlatList component supports scroll loading, which means it can dynamically load more items as the user scrolls down the list.

Pull to Refresh: The FlatList component also supports a pull-to-refresh feature, which allows users to refresh the list by pulling down on it.

ScrollToIndex support: The FlatList component also supports ScrollToIndex, which allows developers to programmatically scroll to a specific item in the list.

Multiple column support: The FlatList component also supports multiple columns. This can be useful in situations where you want to display items in a grid-like layout rather than a single column.

React Native Flatlist Props

As we have discussed before, additional props can be passed to the components in react-native to enhance their functionality. Similarly, FlatList has a list of props to configure the component's behavior and appearance. Let's discuss the essential props used in Flatlist React Native.

data

The data prop is used to specify the array of data that will be rendered in the FlatList. Each item in the array should be an object containing the data that will be rendered. Compatibility: Compatible with both iOS and Android.

Example:

renderItem

The renderItem prop is used to specify the function that will be used to render each item in the FlatList. The function takes an item from the data array as an argument and should return a React component.

Example:

Compatibility: Compatible with both iOS and Android.

  • The FlatList component in React Native offers additional metadata such as the item index, as well as a separators.updateProps function that enables developers to modify the rendering of the leading or trailing separator.
  • This function allows for customization beyond the common highlight and unhighlight methods, which simply set the highlighted: boolean prop.
  • The function takes in several parameters, including the item being rendered, its corresponding index in the data array, and an object of separators.
  • The select parameter is an enum that allows developers to choose whether to modify the leading or trailing separator, and the newProps parameter takes in an object of custom props.

ListHeaderComponent

The ListHeaderComponent prop is used to specify a React component that will be rendered at the top of the list.

Example :-

Compatibility: Compatible with both iOS and Android.

ListFooterComponent

The ListFooterComponent prop is used to specify a React component that will be rendered at the bottom of the list. Example:-

Compatibility: Compatible with both iOS and Android.

initialNumToRender

To improve the perceived performance of scroll-to-top actions, the initialNumToRender prop specifies the number of items to render in the initial batch. It is recommended to set this value to be enough to fill the screen but not much more in flatlist React Native. It's important to note that these items will never be unmounted as part of the windowed rendering.

Example:

In this example, we have a FlatList that renders a list of 10 items. We set initialNumToRender to 5, which means that the FlatList will render the first 5 items when it initially mounts.

This is done for performance reasons, as rendering all 10 items at once can cause performance issues, especially on older devices. As the user scrolls, the FlatList will render more items on demand.

onEndReached

The onEndReached prop is used to specify a function that will be called when the user scrolls to the end of the list.

Example:

Compatibility: Compatible with both iOS and Android.

onRefresh

The onRefresh prop is used to specify a function that will be called when the user pulls down the list to refresh the data.

Example:

Compatibility: Compatible with both iOS and Android.

refreshing

The refreshing prop is used to specify whether the list is currently being refreshed. This prop is typically used in conjunction with the onRefresh prop.

Example:

Compatibility: Compatible with both iOS and Android.

getItemLayout

The getItemLayout prop takes in a function that returns an object with information about the size and position of an item in the list. It's an optional optimization that can improve performance by allowing FlatList React Native to skip the measurement of dynamic content. If you know the size (height or width) of items ahead of time, you can use getItemLayout to efficiently render your list.

For example, if your items have a fixed size, you can specify the getItemLayout prop like this:

This specifies that each item has a length of ITEM_HEIGHT and an offset equal to ITEM_HEIGHT times its index.

Including the separator length (height or width) in your offset calculation is important if you specify ItemSeparatorComponent.

Using getItemLayout can provide a significant performance boost for lists with many items, especially on mobile devices.

horizontal

This prop is used to change the alignment in which the elements are rendered, by default the elements are rendered horizontally from top to bottom but if this prop is set to true, then the flat list renders items next to each other in a horizontal manner from left to right.

keyExtractor

The keyExtractor prop is used to specify a function that extracts a unique key for each item in the data array. The key is used by flatlist React Native to optimize the rendering of the list.

Example:

Compatibility: Compatible with both iOS and Android.

onViewableItemsChanged

In case the viewability of a row is altered this is called, as defined by the 'viewabilityConfig' prop.

React Native Flatlist Methods

FlatList provides a range of methods to manipulate the rendered data. Let's discuss some of the most common methods available in flatlist React Native.

scrollToIndex()

This method allows you to scroll to a particular index. The index parameter specifies the index of the item to which the list should scroll. The viewPosition parameter defines where the specified index should be displayed. It has three possible values: 'start', 'end', or 'center'.

Syntax:

scrollToEnd()

This method enables the FlatList to scroll to the end of the list. If the animated parameter is set to true, the scroll will be animated.

Syntax:

scrollToOffset()

It enables the FlatList to scroll to a particular offset value. Here, the offset is the pixel value to which the list should scroll. The animated parameter is optional. The animated parameter defines whether the scroll should be animated or not.

recordInteraction()

It informs the FlatList about user interaction. This is help full in case you want to prevent the list from scrolling by itself, for example when an application user is actively scrolling the list.

flashScrollIndicators()

This method flashes the scroll indicators of the FlatList, making them visible to the user. This can be useful in scenarios where you want to draw the user's attention to the scrollable content.

getItemLayout()

This method optimizes the rendering performance of the FlatList by allowing you to skip the measurement of dynamic content if you know the size (height or width) of items ahead of time in flatlist react native. This can be a great performance boost for lists of several hundred items.

renderFooter()

This method enables you to render a footer component at the bottom of the list. The footer component can be used to display additional information about the list, such as a loading spinner or a message indicating that there is no more data to load.

Data Display from API

Step 1: Install expo-cli, using the below command npm install -g expo-cli

Step 2: Create a new project by using the following command. expo init Project

Step 3: Change the directory to your project folder, i.e., Project cd Project

In the above code

  • useEffect() will run on the first render and call the fetch API.
  • The fetch API, in turn, is making calls to the URL to get movie data.
  • After successfully fetching data, it is stored in data and the title useState hooks.
  • The set loading is also set to false as data is fetching successfully
  • The data is then parsed to the Flatlist, which renders the content on the screen.

Now, start the server by using the following command.

Output

output

React Native Flatlist Customization

The customization options for the appearance and behavior of FlatList are:-

Header Component

The FlatList provides the capability to include header components. It can be beneficial when you wish to showcase a search bar above a list of contacts. To accomplish this, you can use the ListHeaderComponent property.

In case a user has scrolled down to the end of the list and wishes to return to the top, it would be reasonable to provide a button that takes them up automatically. To achieve this, you can include a footer component to your list to signal the end of the list and provide a convenient way to navigate back to the top.

Separators

The use of Separator components in a list helps in visually differentiating each element, thereby enhancing the overall user interface and experience.

Handling Empty Lists

Suppose you developed a note-taking application using flatlist React Native. In case there are no notes saved by the user, it would be appropriate to display a message stating "No notes found." To accomplish this, you can utilize the ListEmptyComponent prop.

Flatlist Basic Practices

To ensure optimal performance, there are a few key considerations to keep in mind. Below are some tips for using FlatList effectively.

Use Lighter Components

The heavier your components are, the more memory they consume. To improve performance, display as little information as possible on your list item. This also has the added benefit of creating a cleaner UI.

For items that require a lot of text, use React Navigation. When the user taps on an item, they will be directed to a separate page that displays the remaining details.

Avoid Anonymous Functions

Using anonymous functions in your FlatList can create unnecessary memory usage and consume CPU resources. Instead, define your function outside of the FlatList and pass it as a prop.

Here is an example of the correct way to define your function:

Q. This is a Question

A. This is the answer

FAQs

Ques: Can FlatList be used with both iOS and Android?

Ans: Yes, React Native FlatList is compatible with both iOS and Android devices and provides consistent behavior across platforms. The props and methods available in FlatList are also compatible with both platforms.

Ques: Is FlatList scrollable?

Ans: FlatList provides scrollable features by default. It loads items that are currently visible on the screen and removes these items as they go off the screen.

Ques: How to display data from an API using FlatList?

Ans: To display data from an API using React Native FlatList, you can use the fetch API to request the API. Then pass this data to the data prop, and render each item in the list using renderItem prop.

:::

Conclusion

In summary, Flatlist React Native is a powerful tool for displaying large amounts of data. This article provided an overview of FlatList and its advantages, along with a detailed explanation of its features, props, and methods. Additionally, it offered a step-by-step guide on how to display data from an API using FlatList and explored customization options such as styling and layout.