I have recently started using react-native
and have come across the FlatList
component. When using react
I have always used map
with an array.
I was using FlatList
but there was issues when I wanted to change the flex-direction
of items in the FlatList
so I reverted to using map
.
Here are the two examples using both methods:
map
{
this.state.images.map(image => {
return (
<UsersImage key={ image } source={{ uri: image }} />
)
})
}
FlatList
<FlatList
data={ this.state.images }
renderItem={({item}) => {
return (
<UsersImage source={{ uri: item }} />
)
}}
keyExtractor={(item, index) => index}
/>
Can anyone explain why one should use FlatList
over map
or vice versa?
I have recently started using react-native
and have come across the FlatList
component. When using react
I have always used map
with an array.
I was using FlatList
but there was issues when I wanted to change the flex-direction
of items in the FlatList
so I reverted to using map
.
Here are the two examples using both methods:
map
{
this.state.images.map(image => {
return (
<UsersImage key={ image } source={{ uri: image }} />
)
})
}
FlatList
<FlatList
data={ this.state.images }
renderItem={({item}) => {
return (
<UsersImage source={{ uri: item }} />
)
}}
keyExtractor={(item, index) => index}
/>
Can anyone explain why one should use FlatList
over map
or vice versa?
- Hi Peter, would you consider accepting my answer if you found it helpful? – R u c k s a c k Commented Jul 6, 2021 at 9:08
3 Answers
Reset to default 28FlatList has lazy loading (it only shows what's on screen, so it can be more performant if you have a huge list). BTW you can get it to be horizontal if that's what you needed to change the flex direction for - just pass the horizontal
prop (equivalent to saying horizontal={true}
)
The FlatList
displays the similarly structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time. The FlatList
shows only those render elements that are currently displaying on the screen, not all the elements of the list at once. So that's the main reason FlatList
can handle a large set of data with a very complex view easily.
The map()
function is used to iterate over an array and manipulate or change data items. In React, the map()
function is most commonly used for rendering a list of data to the DOM.
In react-native FlatList
is recommended over map()
when we need to display a large scrollable list.
no need to flex your View tags. just add horizontal
<FlatList
horizontal
data={data}
renderItem={(item) => this.renderItem(item.item)}
keyExtractor={(item, index) => index}
/>