React Native FlatList Example

I’m going to show you a quick and concise example of FlatList and how to use it in React Native to make a simple or personalized list.

If you don’t have a project already create a new one using this classic command.

react-native init flatlist

Open App.js and make sure you have this in it. We don’t need any extra libraries for this example, all is provided in react-native.

  • I created a simple state object that has an array called data.
  • Data holds objects that have two properties: title and key. (You can have any property you want and name them anything you want)

Inside render() we return a basic view with a FlatList in it to keep this example short.

Let’s discuss the FlatList props.

  • data is the actual stuff that will be displayed in the links.
  • extraData when you change the object you passed here it will force re-render the list. Read more about FlatList and PureComponent here.
  • keyExtractor is how you want to uniquely identify rows in the list. Here the keys are ‘m’, ‘t’, ‘s’ but you could create any id by composing variables from the object or using the index (which is 0, 1, 2… etc).
  • renderItem is the function that gets called for each element and decides how to display it (text, styles etc).
import React from 'react';
import {FlatList, View, Text} from 'react-native';

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          title: 'Monday', 
          key: 'm',
        }, 
        {
          title: 'Tuesday', 
          key: 't'
        }, 
        {
          title: 'Superglobals.net',
          key: 's'
        }
      ]
    }
  }

  render() {
    return (
      <View>
        <FlatList data={this.state.data} extraData={this.state} keyExtractor={(item, index) => item.key} renderItem={({item, index}) => (
          <View>
            <Text>{item.title}</Text>
          </View>
        )}/>
      </View>
    );
  }
}

For now we have our renderItem to return a simple <View> with some <Text> made of item’s title property.

Let’s run this FlatList example using the React Native cli.

react-native run-android
react native flatlist example

Not exactly a looker but we will improve. Let’s create a custom component that will render for each row.

Create a new file called Item.js. Notice we extend PureComponent instead of simply component. We do this in order not to re-render every item when only one item changes.

  • we will pass index as a prop to this component to make row have two colors (make it more readable and nicer looking).
  • title and id will also be passed as properties and wrapped inside a TouchableOpacity because we want to add some click action to it.
import React from 'react';
import {TouchableOpacity, View, Text, StyleSheet,} from 'react-native';

export default class Item extends React.PureComponent {

    render() {
        const listItemStyle = this.props.index % 2 == 0 ? styles.even : styles.odd;
        return (
            <View style={styles.listItem}> 
                    <TouchableOpacity style={[listItemStyle, styles.fillWidth]}>
                        <Text style={styles.text}>
                            {this.props.title + ': ' + this.props.id}
                        </Text>
                    </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    listItem: {
        borderBottomWidth: 1, 
        borderColor: '#010101', 
        backgroundColor: '#B0D078', 
        flexDirection: 'row', 
        justifyContent: 'space-between'
    },
    odd: {
        backgroundColor: '#FFFFFF'
    },
    even: {
        backgroundColor: '#D7E2F8'
    },
    fillWidth: {
        flex: 1
    },
    text: {
        color: "black", 
        margin: 5, 
        fontSize: 14
    }
});

Let’s improve our React Native FlatList example by using the new component. Open App.js and import the new component.

import Item from './Item';

Modify the FlatList so it looks like this. We pass id, title and index as props.

<FlatList data={this.state.data} extraData={this.state} keyExtractor={(item, index) => item.key} renderItem={({item, index}) => (
      <Item id={item.key} title={item.title} index={index}/> 
)}/>

Now it looks like this. Way better!

react native flatlist example

Now to further complicate our example let’s make the React Native FlatList react to actions!

Add this in App.js. Don’t forget the import.

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

It will display a dialog showing the clicked item title.

onPressItem = (title) => {
    Alert.alert('You pressed ' + title);
}

We pass this function reference also like a prop to the Item component.

<Item id={item.key} title={item.title} index={index} onPressItem = {this.onPressItem}/> 

Inside Item.js we add it as the onPress property.

<TouchableOpacity style={[listItemStyle, styles.fillWidth]} onPress={() => this.props.onPressItem(this.props.title)}>
   <Text style={styles.text}>
        {this.props.title + ': ' + this.props.id}
   </Text>
</TouchableOpacity>

Let’s test our fully functioning example of React Native FlatList.

react native flatlist example
App.js
import React from 'react';
import {FlatList, View, Alert} from 'react-native';
import Item from './Item';

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          title: 'Monday', 
          key: 'm',
        }, 
        {
          title: 'Tuesday', 
          key: 't'
        }, 
        {
          title: 'Superglobals.net',
          key: 's'
        }
      ]
    }
  }

  onPressItem = (title) => {
    Alert.alert('You pressed ' + title);
  }

  render() {
    return (
      <View>
        <FlatList data={this.state.data} extraData={this.state} keyExtractor={(item, index) => item.key} renderItem={({item, index}) => (
          <Item id={item.key} title={item.title} index={index} onPressItem = {this.onPressItem}/> 
        )}/>
      </View>
    );
  }
}
Item.js
import React from 'react';
import {TouchableOpacity, View, Text, StyleSheet,} from 'react-native';

export default class Item extends React.PureComponent {

    render() {
        const listItemStyle = this.props.index % 2 == 0 ? styles.even : styles.odd;
        return (
            <View style={styles.listItem}> 
                    <TouchableOpacity style={[listItemStyle, styles.fillWidth]} onPress={() => this.props.onPressItem(this.props.title)}>
                        <Text style={styles.text}>
                            {this.props.title + ': ' + this.props.id}
                        </Text>
                    </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    listItem: {
        borderBottomWidth: 1, 
        borderColor: '#010101', 
        backgroundColor: '#B0D078', 
        flexDirection: 'row', 
        justifyContent: 'space-between'
    },
    odd: {
        backgroundColor: '#FFFFFF'
    },
    even: {
        backgroundColor: '#D7E2F8'
    },
    fillWidth: {
        flex: 1
    },
    text: {
        color: "black", 
        margin: 5, 
        fontSize: 14
    }
});
FacebookTwitterLinkedin