0
0
React Nativemobile~5 mins

FlatList basics (data, renderItem, keyExtractor) in React Native

Choose your learning style9 modes available
Introduction

FlatList helps show a list of items on the screen in a smooth and fast way. It makes scrolling easy and efficient.

When you want to show a list of messages in a chat app.
When you want to display a list of contacts or friends.
When you want to show a list of products in a shopping app.
When you want to show a list of tasks or reminders.
When you want to display any long list that can scroll.
Syntax
React Native
import { FlatList, Text, View } from 'react-native';

<FlatList
  data={arrayOfItems}
  renderItem={({ item }) => <Text>{item.name}</Text>}
  keyExtractor={item => item.id}
/>

data is the list of items you want to show.

renderItem tells how to show each item.

keyExtractor gives a unique key for each item to help React Native manage the list efficiently.

Examples
Shows a simple list of fruits with unique ids.
React Native
const fruits = [{ id: '1', name: 'Apple' }, { id: '2', name: 'Banana' }];

<FlatList
  data={fruits}
  renderItem={({ item }) => <Text>{item.name}</Text>}
  keyExtractor={item => item.id}
/>
Shows what happens if the list is empty: nothing is shown.
React Native
const emptyList = [];

<FlatList
  data={emptyList}
  renderItem={({ item }) => <Text>{item.name}</Text>}
  keyExtractor={item => item.id}
/>
Shows a list with only one item.
React Native
const singleItem = [{ id: '100', name: 'Only One' }];

<FlatList
  data={singleItem}
  renderItem={({ item }) => <Text>{item.name}</Text>}
  keyExtractor={item => item.id}
/>
Sample App

This app shows a list of animal names using FlatList. Each animal has a unique id used as the key. The list is scrollable if needed.

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

export default function App() {
  const animals = [
    { id: 'a1', name: 'Dog' },
    { id: 'a2', name: 'Cat' },
    { id: 'a3', name: 'Elephant' }
  ];

  return (
    <SafeAreaView style={{ flex: 1, marginTop: 50 }}>
      <FlatList
        data={animals}
        renderItem={({ item }) => <Text style={{ fontSize: 24, padding: 10 }}>{item.name}</Text>}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}
OutputSuccess
Important Notes

FlatList only renders items visible on the screen for better performance.

Always provide a unique keyExtractor to avoid warnings and improve list updates.

Common mistake: forgetting keyExtractor or using non-unique keys causes rendering issues.

Summary

FlatList shows lists efficiently by rendering only visible items.

Use data to give the list items, renderItem to show each item, and keyExtractor to give unique keys.

This helps your app run smoothly and look good when showing lists.