How to use a keyExtractor with FlatList with React Native?

Sometimes, we want to use a keyExtractor with FlatList with React Native.

In this article, we’ll look at how to use a keyExtractor with FlatList with React Native.

How to use a keyExtractor with FlatList with React Native?

To use a keyExtractor with FlatList with React Native, we can set keyExtractor to a function that returns the unique ID value for each entry.

For instance, we write:

import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const flatListItems = Array(200)
  .fill()
  .map((_, i) => ({ title: i, id: i }));

const Item = ({ title }) => (
  <View
    style={{
      backgroundColor: '#f9c2ff',
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
    }}>
    <Text>{title}</Text>
  </View>
);

export default function App() {
  const renderItem = ({ item }) => <Item title={item.title} />;

  return (
    <View>
      <FlatList
        data={flatListItems}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </View>
  );
}

to set keyExtractor to (item) => item.id to return the id property of a flatListItems entry.

Conclusion

To use a keyExtractor with FlatList with React Native, we can set keyExtractor to a function that returns the unique ID value for each entry.