React FlatList renderItem

Julian picture Julian · Aug 1, 2017 · Viewed 36.1k times · Source

I've seen this sort of syntax in JS before and I am just curious how it works. In the React Native Docs for FlatList, an example calls renderItem. How does this._renderItem know that what individual list item it is working with? It looks like item is being destructured, but from what object?

_renderItem = ({item}) => (
    <MyListItem
        id={item.id}
        onPressItem={this._onPressItem}
        selected={!!this.state.selected.get(item.id)}
        title={item.title}
    />
);

render() {
    return (
        <FlatList
            data={this.props.data}
            extraData={this.state}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
        />
    );
}

Put differently: in FlatList, another way to make this same call could be:

<FlatList <other props> renderItem={({item}) => (<MyListItem ....) />

Is renderItem some special prop where {item} will always be the destructured arg?

Answer

Balasubramanian picture Balasubramanian · Aug 1, 2017

data prop - need to pass an array of data to the FlatList via the data prop. That’s available on this.props.data.

renderItem prop - Then you want to render the content with the renderItem prop. The function is passed a single argument, which is an object. The data you’re interested in is on the item key so you can use destructuring to access that from within the function. Then return a component using that data.

render() {
 return (
    <List>
      <FlatList
        data={this.state.data}
        renderItem={({ item }) => (
          // return a component using that data
        )}
      />
    </List>
 );
}