Building Lists
The FlatList
Element
FlatList
ElementThe FlatList
primitive element takes an array of items and turns it into a list of elements.
FlatList
takes 2 props:
data
: accepts arrayrenderItem
: function that turns each item into an element
Note: React Native prefers FlatList
over the generic map
method because it adds performance optimizations for list rendering on mobile.
Using FlatList
FlatList
Here's how FlatList
looks in code:
Notice how the element passed into renderItem
is not exactly each object in the friends
array. React Native adds a bunch of extra properties to each object, and it places your item in the item
property. (Most of the time you only really care about the item
property.)
The key
Property
key
PropertyWhy use the key
property
key
propertyWithout a key
property, React Native can't keep track of items in a list. That means if you change one element in an array, React Native has to re-render every element. The key
property is required for performance optimization.
How to add the key
property
key
propertyThere are 2 ways to add a key
property each element in a FlatList
:
Include a
key
property in each object in your input array.{ name: 'Friend #1', key: '1' }
The only requirement here is that
key
must be a string.Each
key
must be unique.
Use
keyExtractor
prop inFlatList
This function receives each item in your array, and you're expected to return a unique string representing the
key
.
Pro tip: We will generally prefer the keyExtractor
approach because you generally don't want your view-related data mixed up with actual data.
A Few Props in FlatList
FlatList
FlatList
gives us a few more useful props that you should know:
horizontal
makes the list render horizontally.showsHorizontalScrollIndicator
can hide or display the scrollbar that appears when you scroll horizontally
Last updated