React FlatList renderItem
I've seen this kind of syntax in JS before and I'm just wondering how it works. In React Native Docs for FlatList, the example calls renderItem. How does this._renderItem know which individual list item it is working with? It looks like the item is being destroyed, but from which object?
In other words, another call can be made in Flatlist:
<FlatList <other props> renderItem={({item}) => (<MyListItem ....) />
Is renderItem some kind of special prop where {item} will always be a destructured argument?
source to share
data prop - you need to pass an array of data to FlatList using data prop
. It is available on this .props.data file.
renderItem prop . Then you want to display the content using renderItem
prop. The function is passed in one argument, which is an object. The data you are interested in is on item key
, so you can use destructuring to access that function inside the function. Then return the component using this data.
render() {
return (
<List>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
// return a component using that data
)}
/>
</List>
);
}
source to share
adding on to what @Balasubramanian said renderItem
points to current item
, and since you are using a component List
as a wrapper, you can also use a "ListItem" component inside a function renderItem
for render
data current item
something like this:
renderItem={({ item, index }) => {
return (
<ListItem
key={index}
title={item.name}
onPress={ () => this.assetSelected(item) }
/>
);
}
source to share