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.

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

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

renderItem={(item) => <Text> {item.item.name} </Text>}
What is the reason for this behavior.
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>}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With