A Complete Guide on Flatlist in React Native

July 30,2024

If you're developing with React Native, mastering the FlatList component is crucial. FlatList in react native isn't just another component; it's a dynamic, highly efficient way to easily display lists that can handle updates and large data sets. Let's dive deep into the world of FlatList, exploring its structure, functionalities, and flatlist in react native example in a way that's easy to grasp and implement.

What is FlatList in React Native?

The first and basic question that needs to be answered is: “What is flatlist in react native?”. FlatList is a core component in React Native, one of the best front-end technologies, designed to render scrollable lists efficiently. Unlike basic mapping functions that render all elements at once, react native FlatList only renders items that are currently visible on the screen. This makes it an ideal choice for handling large data sets with minimal performance overhead.

Introduction to FlatList Component

The FlatList component in react native displays a collection of structured data in a scrollable format. It only renders the visible elements, making it highly efficient for long lists. 

    
        import React from 'react';
        import { FlatList, Text, View } from 'react-native';
        const DATA = [
        { id: '1', title: 'Item 1' },
        { id: '2', title: 'Item 2' },
        { id: '3', title: 'Item 3' },
        // Add more items
        ];

        const App = () => {
        return (
         {item.title}}
        keyExtractor={item => item.id}
        />
        );
        };

export default App;

What is FlatList in React Native?

The first and basic question that needs to be answered is: “What is flatlist in react native?”. FlatList is a core component in React Native, one of the best front-end technologies, designed to render scrollable lists efficiently. Unlike basic mapping functions that render all elements at once, react native FlatList only renders items that are currently visible on the screen. This makes it an ideal choice for handling large data sets with minimal performance overhead.

Introduction to FlatList Component

The FlatList component in react native displays a collection of structured data in a scrollable format. It only renders the visible elements, making it highly efficient for long lists. Code

"Props" refers to properties. These are additional parameters passed into a component. Flatlist component in React native can have both essential and optional props that are necessary for their usage. FlatList in react native offers a variety of properties that enhance its flexibility and functionality:

  • ItemSeparatorComponent: Component to render between each item.
  • ListEmptyComponent: This component is displayed when the list is empty.
  • ListHeaderComponent: Component rendered at the top of the list.
  • ListFooterComponent: Component rendered at the bottom of the list.
  • horizontal: Renders the list horizontally (default is vertical).
  • initialNumToRender: The number of items to render initially.
  • onEndReached: The function is used when the end of the list is reached.
  • onRefresh: Function to call when a pull-to-refresh is started.
  • columnWrapperStyle: This is a custom style used for multi-item rows.
  • refreshing: A Boolean to show the refresh status (controlled by onRefresh).
  • progressViewOffset: It is set when the loading offset is required. It is only available for Android devices.
  • extraData: Data besides data that the list might depend on to re-render. inverted: Reverses the direction of the scroll.
  • removeClippedSubviews: This may improve scroll performance when scrolling through long lists. The default value on Android is true.
  • viewabilityConfigCallbackPairs: Displays a list of pairs.

Props of FlatList in React Native

"Props" refers to properties. These are additional parameters passed into a component. Flatlist component in React native can have both essential and optional props that are necessary for their usage. FlatList in react native offers a variety of properties that enhance its flexibility and functionality:

  • ItemSeparatorComponent: Component to render between each item.
  • ListEmptyComponent: This component is displayed when the list is empty.
  • ListHeaderComponent: Component rendered at the top of the list.
  • ListFooterComponent: Component rendered at the bottom of the list.
  • horizontal: Renders the list horizontally (default is vertical).
  • initialNumToRender: The number of items to render initially.
  • onEndReached: The function is used when the end of the list is reached.
  • onRefresh: Function to call when a pull-to-refresh is started.
  • columnWrapperStyle: This is a custom style used for multi-item rows.
  • refreshing: A Boolean to show the refresh status (controlled by onRefresh).
  • progressViewOffset: It is set when the loading offset is required. It is only available for Android devices.
  • extraData: Data besides data that the list might depend on to re-render. inverted: Reverses the direction of the scroll.
  • removeClippedSubviews: This may improve scroll performance when scrolling through long lists. The default value on Android is true.
  • viewabilityConfigCallbackPairs: Displays a list of pairs.

Core Features of React Native FlatList

React native FlatList is not just efficient but also comes packed with features that make it highly customizable:

  • Efficient Scrolling: It renders only the visible items, reducing the amount of memory and computation needed.
  • ListEmptyComponent: This component is displayed when the list is empty.
  • Flexibility: Offers numerous properties to customize the appearance and behavior of the list.
  • ListFooterComponent: Component rendered at the bottom of the list.
  • Horizontal and Vertical Layouts: Supports both horizontal and vertical list layouts.
  • Built-in Refresh Control: Easily implement pull-to-refresh functionality.
  • Header and Footer Support: Add custom components as headers and footers.
  • Item Separation: Automatically add separators between items.

Key Properties of React Native FlatList

The Flatlist component in react native is divided into these props: Basic Props

Basic Props

  • data: The array of items to be displayed.
  • renderItem: A function that takes an individual item from the data and renders it into the list.
  • keyExtractor: A function that extracts a key for each item.

Customization Props

  • ItemSeparatorComponent: Renders a component between list items.
  • ListHeaderComponent: Component rendered at the top of the list.
  • ListFooterComponent: Component rendered at the bottom of the list.
  • horizontal: Boolean, which determines if the list should scroll horizontally rather than vertically.

Benefits of React Native FlatList Components

FlatList in react native is not just about performance; it also offers flexibility and a range of features that make it ideal for modern mobile app development:

  • Efficient Rendering: FlatList conserves device resources and handles updates efficiently by only rendering visible items.
  • renderItem: A function that takes an individual item from the data and renders it into the list.
  • Flexibility: With extensive props, FlatList can be customized to meet various UI requirements.
  • Interactive Features: Built-in pull-to-refresh and page break capabilities make it interactive and user-friendly.

How to Implement FlatList

Basic Structure

To start using react native FlatList, you need to import it from the React Native library and specify at least two props: data and renderItem. Here's a simple Flatlist in React native example to illustrate:

  
    import React from 'react';
    import { FlatList, Text, View } from 'react-native';
    
    const DATA = [
    { id: '1', title: 'Item 1' },
    { id: '2', title: 'Item 2' },
    { id: '3', title: 'Item 3' },
    // Add more items
  ];
  
  const App = () => {
    return (
       {item.title}}
        keyExtractor={item => item.id}
      />
    );
  };
  
  export default App;
  

This code snippet will render a vertical list of text items.

Advanced Use-Cases

1. Handling Large Datasets

FlatList can handle large datasets by only rendering items that are visible. This is ideal for applications like social media feeds or email clients.

            
              import React, { useState, useEffect } from 'react';
              import { FlatList, Text, View, ActivityIndicator } from 'react-native';
              
              const App = () => {
                const [data, setData] = useState([]);
                const [loading, setLoading] = useState(true);
              
                useEffect(() => {
                  fetch('https://api.example.com/data')
                    .then(response => response.json())
                    .then(json => {
                      setData(json);
                      setLoading(false);
                    });
                }, []);
              
                if (loading) {
                  return ;
                }
              
                return (
                   {item.title}}
                    keyExtractor={item => item.id}
                  />
                );
              };
              
              export default App;
              
            
          
          

2. Customizing Item Separators

Use ItemSeparatorComponent to customize the separators between items for better visual distinction.

          
            import React from 'react';
import { FlatList, Text, View } from 'react-native';

const DATA = [
  { id: '1', title: 'Item 1' },
  { id: '2', title: 'Item 2' },
  { id: '3', title: 'Item 3' },
  // Add more items
];

const ItemSeparator = () => ;

const App = () => {
  return (
     {item.title}}
      keyExtractor={item => item.id}
      ItemSeparatorComponent={ItemSeparator}
    />
  );
};

export default App;

            
          
        
        

3. Horizontal Lists

Set the horizontal prop to true to create a horizontal list.

          
            import React from 'react';
import { FlatList, Text, View } from 'react-native';

const DATA = [
  { id: '1', title: 'Item 1' },
  { id: '2', title: 'Item 2' },
  { id: '3', title: 'Item 3' },
  // Add more items
];

const App = () => {
  return (
     {item.title}}
      keyExtractor={item => item.id}
      horizontal={true}
    />
  );
};

export default App;


            
          
        
        

4. Multiple Columns

Use the numColumns prop to display items in multiple columns instead of a single column.

          
            import React from 'react';
            import { FlatList, Text, View } from 'react-native';
            
            const DATA = [
              { id: '1', title: 'Item 1' },
              { id: '2', title: 'Item 2' },
              { id: '3', title: 'Item 3' },
              // Add more items
            ];
            
            const App = () => {
              return (
                 {item.title}}
                  keyExtractor={item => item.id}
                  numColumns={2}
                />
              );
            };
            
            export default App;
            

            
          
        
        

Advanced FlatList Features

1. Performance Enhancements

FlatList's initialNumToRender and onEndReached properties help manage how and when data is loaded, improving your application's responsiveness.

2. Customization with Components

You can customize FlatList further with ListHeaderComponent and ListFooterComponent, adding static headers or footers and ItemSeparatorComponent for custom separators.

Practical Tips for FlatList

  • Handling Large Data Sets: Use the onEndReached prop to load more data dynamically as the user scrolls, which is ideal for data fetched from the internet.
  • Refreshing Data: Implement the onRefresh and refreshing props for pull-to-refresh functionality, enhancing user interaction.

React Native FlatList Syntax (With Sample Usage)

Here's a more detailed flatlist in React native example showcasing a FlatList with multiple customization options:

          
            mport React, { useState } from 'react';
            import { FlatList, Text, View, Button } from 'react-native';
            
            const DATA = [
              { id: '1', title: 'Item 1' },
              { id: '2', title: 'Item 2' },
              { id: '3', title: 'Item 3' },
              // Add more items
            ];
            
            const App = () => {
              const [refreshing, setRefreshing] = useState(false);
            
              const onRefresh = () => {
                setRefreshing(true);
                // Fetch new data here and update state
                setTimeout(() => setRefreshing(false), 2000);
              };
            
              return (
                 {item.title}}
                  keyExtractor={item => item.id}
                  ItemSeparatorComponent={() => }
                  ListHeaderComponent={() => Header}
                  ListFooterComponent={() => Footer}
                  onRefresh={onRefresh}
                  refreshing={refreshing}
                />
              );
            };
            export default App;
            
            
          
        
        

Methods in FlatList

The Flatlist in react native functional component includes several methods that enhance its functionality, allowing for more control and interactivity:

  • scrollToEnd(): Scroll to the end of the list.
  • scrollToIndex(params): Scrolls to a specific index in the list.
  • scrollToOffset(params): Scrolls to a specific offset in the list.

These methods can be triggered programmatically to control the list's scroll behavior, offering a dynamic user experience.

Comparing FlatList with Other Components

FlatList vs. ScrollView:

  • React native flatlist is suited for long lists with dynamic data where only visible items are rendered.
  • ScrollView renders all children at once, making it less efficient for long lists but suitable for small, static views.

FlatList vs. SectionList:

  • FlatList in React native functional component is straightforward and great for simple lists.
  • SectionList is used when you need to categorize data into sections, each with its own header.

Conclusion

FlatList in React native is a robust component crucial for optimizing list rendering in React Native web development frameworks. Its efficiency in handling large lists and its extensive customization options make it an essential tool for any React Native developer. Understanding what is flatlist in react native and leveraging it allows you to create fast, responsive, and engaging applications that perform well across devices. For a more better and practical approach, you should consider consulting Invoidea and hiring their React Native Developers so that you will get the best.

profile

Deblina Chakraborty

Content Specialist at InvoIdea Technologies Pvt. Ltd.

Join Us

Get the latest updates on design, development, and technology trends right in your inbox.

Related Posts

This website uses cookies to provide you with a great user experience. By using it, you accept our use of cookies