What is the FlatList component and how to use it in React Native?

React NativeJavascriptMobile Development

FlatList is a container that can be used to load the list items. It offers header and footer support, multiple column support, comes with vertical/horizontal scrolling, lazy loading etc.

Here are some important features of FlatList −

  • Comes with scroll loading
  • Able to adjust the scroll by using ScrolltoIndex support
  • Comes with header and footer support
  • Multiple column support
  • Cross platform
  • Configurable viewability callbacks

The Basic structure of FlatList is as follows −

<FlatList
data={DataContainer} renderItem={ yourenderItem} keyExtractor={item => item.id} />

FlatList is implemented from the VirtualizedList component that takes care of displaying a limited number of items that will fit in the current view port of your mobile screen. The rest of the data is rendered as the user scrolls. The basic props like data and renderItem can be used to create a FlatList.

To work with FlatList you need to import it from react-native as follows −

import { FlatList} from "react-native";

Some of the important Properties of FlatList are listed below −

PropsDescription
dataAn array that has the data to be displayed.
renderItemrenderItem({ item, index, separators });

  • item − It is the item from the data field that is displayed in the list format.
  • index − Each item is given an index.
  • separators − is a function that helps to render the props.The function available are −

separators.highlight(),
separators.unhighlight(),
separators.updateProps().
ListEmptyComponentA component class, a render function or a render element that will get invoked when the list is empty. In case you want to do something when the list is empty this component will be helpful.
ListFooterComponentA component class, a render function or a render element that will get rendered at the bottom of all the items.
ListFooterComponentStylestyling required for the footer component can be done here.
ListHeaderComponentA component class, a render function or a render element that will get rendered at the top of all the items.
ListHeaderComponentStylestyling required for the header component can be done here.
horizontalThis property if set to true will render the items horizontally.
keyExtractorExtracts the unique key for the given index.The key is used for caching and also used to track item re-ordering.(item: object, index: number) => string;

Example 1: Displaying items in FlatList Vertically

The example shows the working of FlatList. To work with FlatList import the component first −

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

I need FlatList as well other components like Text, View, StyleSheet, etc. The same are imported as shown above.

Once the import is done, I need the data to be shown in the FlatList. The data is stored inside this.state.data as shown below −

this.state = {
   data: [
      { name: "Javascript Frameworks", isTitle: true },
      { name: "Angular", isTitle: false },
      { name: "ReactJS", isTitle: false },
      { name: "VueJS", isTitle: false },
      { name: "ReactNative", isTitle: false },
      { name: "PHP Frameworks", isTitle: true },
      { name: "Laravel", isTitle: false },
      { name: "CodeIgniter", isTitle: false },
      { name: "CakePHP", isTitle: false },
      { name: "Symfony", isTitle: false }
   ],
   stickyHeaderIndices: []
};

To implement function for renderItem

The function below takes care of taking the item and displaying the same in the Text component as shown below −

renderItem = ({ item }) => {
   return (
      <View style={styles.item}>
         <Text style={{ fontWeight: (item.isTitle) ? "bold" : "", color: (item.isTitle) ? "red" : "gray"}} >{item.name}</Text>
      </View>
   );
};

The Text component is wrapped inside the View Component. The item.isTitle is variable is checked if its true/false, and accordingly it is made bold, as well the color is given to it.

To implement FlatList

Here is the FlatList implementation that has data and renderItem props.

<View style={styles.container}>
   <FlatList data={this.state.data} renderItem={this.renderItem} keyExtractor={item => item.name} />
</View>

The this.state.data is given to the data props and the this.renderItem function is assigned to renderItem props.

Based on your data you can tell the key property that will be a unique one from the data array and the same should be given to the props keyExtractor.If not given it will consider the array index as the key value.

So we have considered the name as the unique Key and the same is assigned to keyExtractor.

keyExtractor={item => item.name}

Here is the full code that implements FlatList.

import React from "react";
import { FlatList , Text, View, StyleSheet, StatusBar } from "react-native";
export default class App extends React.Component {
   constructor() {
      super();
      this.state = {
         data: [
            { name: "Javascript Frameworks", isTitle: true },
            { name: "Angular", isTitle: false },
            { name: "ReactJS", isTitle: false },
            { name: "VueJS", isTitle: false },
            { name: "ReactNative", isTitle: false },
            { name: "PHP Frameworks", isTitle: true },
            { name: "Laravel", isTitle: false },
            { name: "CodeIgniter", isTitle: false },
            { name: "CakePHP", isTitle: false },
            { name: "Symfony", isTitle: false }
         ],
         stickyHeaderIndices: []
      };
   }
   renderItem = ({ item }) => {return (<View style={styles.item}><Text style={{ fontWeight: (item.isTitle) ? "bold" : "", color: (item.isTitle) ? "red" : "gray"}} >{item.name}</Text></View>);};
render() {
   return (<View style={styles.container}><FlatList data={this.state.data} renderItem=   {this.renderItem} keyExtractor={item => item.name} stickyHeaderIndices={this.state.stickyHeaderIndices} /></View>);
   }
}
const styles = StyleSheet.create({
   container: {
      flex: 1,
      marginTop: StatusBar.currentHeight || 0,
   },
   item: {
      margin: 10,
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
   }
});

Output

Example 2: Displaying items in FlatList Horizontally

To display FlatList items horizontally you just have to add the props horizontal={true} to your FlatList component.

import React from "react";
import { FlatList , Text, View, StyleSheet, StatusBar } from "react-native";
export default class App extends React.Component {
   constructor() {
      super();
      this.state = {
         data: [
            { name: "Javascript Frameworks", isTitle: true },
            { name: "Angular", isTitle: false },
            { name: "ReactJS", isTitle: false },
            { name: "VueJS", isTitle: false },
            { name: "ReactNative", isTitle: false },
            { name: "PHP Frameworks", isTitle: true },
            { name: "Laravel", isTitle: false },
            { name: "CodeIgniter", isTitle: false },
            { name: "CakePHP", isTitle: false },
            { name: "Symfony", isTitle: false }
         ],
         stickyHeaderIndices: []
      };
   }
   renderItem = ({ item }) => {return (<View style={styles.item}><Text style={{ fontWeight: (item.isTitle) ? "bold" : "", color: (item.isTitle) ? "red" : "gray"}} >{item.name}</Text></View>);};
   render() {
      return (<View style={styles.container}><FlatList horizontal={true}    data={this.state.data} renderItem={this.renderItem} keyExtractor={item => item.name}    stickyHeaderIndices={this.state.stickyHeaderIndices} /></View>);
   }
}
const styles = StyleSheet.create({
   container: {
      flex: 1,
      marginTop: 100,
   },
   item: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      padding: 30,
      margin: 2,
      borderColor: '#2a4944',
      borderWidth: 1,
      height:100,
      backgroundColor: '#d2f7f1'
   }
});

Output

raja
Published on 01-Jul-2021 07:39:01
Advertisements