Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native's FlatList prop renderItem requires extra "item" (item) => {item.item.name}?

Here I am trying to display an array called "posts" in a FlatList.

render() {
    console.log(this.props.posts);
    return (
        <View style={this.styles.container}>
            <FlatList
                data={this.props.posts}
                renderItem={(item) => <Text> {item.name} </Text>}
            />
        </View>
    );
}

As seen in this console log, the posts array is correctly populated. enter image description here

But the above code doesn't display any data in the FlatList.

enter image description here

However, in renderItem, if I add an extra "item" property it works.

enter image description here

renderItem={(item) => <Text> {item.item.name} </Text>}

What is the reason for this behavior.

like image 246
enzio902 Avatar asked Jan 25 '26 11:01

enzio902


2 Answers

Input of ReactNative's FlatList is not item, but an object containing 3 parameters: item for actual data, index for index and separators object to customize your item component. What you did is naming that object item, and get actual item from the object.

To avoid confusion, consider using ES6 shorthand:

renderItem={({ item, index }) => <Text> {item.name} </Text>}

like image 99
blaz Avatar answered Jan 28 '26 00:01

blaz


This is a common behavior. You can get required behavior by doing object destructuring as:

<FlatList
    data={this.props.posts}
    renderItem={({item}) => <Text> {item.name} </Text>}
/>

If you are rendering complex component, then you might want to do like this for sake of readability of the code however.

<FlatList
    data={this.props.posts}
    renderItem={this.renderItem} />

renderItem = ({item}) => {
    return (
      <Text>{item.name}</Text>
    )
}

Might wanna look into your question here though.

ReactNative Flatlist - RenderItem not working

like image 23
Roshan Gautam Avatar answered Jan 27 '26 23:01

Roshan Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!