I am trying to render array DATA using two way: Normal View and FlatList. What I learnt, we pass props in map and renderItem.
First block gives correct output:
const DATA = [
{id: '1',title: 'First Item'},
{id: '2',title: 'Second Item'},
]
const list = DATA.map((lst)=>{
return(<Text key={lst.id}>{lst.title}</Text>)
})
const Home=()=>{
return (<View><Text>{list}</Text></View>)
}
export default Home
In following FlatList Component, it throws error:
TypeError:TypeError:undefined is not an object(evaluating 'lst.title')
If I change lst to Item, then it shows correct output. Is item a predefined keyword in renderItem? If I change item to any other words, it throw error.
const DATA = [
{id: '1',title: 'First Item'},
{id: '2',title: 'Second Item'},
]
const Itm=({title})=>{
return (
<View>
<Text>{title}</Text>
</View>
);
}
const Home=()=>{
return (
<FlatList
data={DATA}
renderItem={({lst}) => <Itm title={lst.title} />}
keyExtractor={itm => itm.id}
/>
);
}
export default Home
The problem is that in your renderItem you are destructuring your object reading the lst keyword:
renderItem={({lst}) => <Itm title={lst.title} />} //Wrong
You are trying to read property lst in an object that doesn't have that key.
change ({lst}) to (lst):
renderItem={(lst) => <Itm title={lst.title} />}
You can read about object destructuring in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
EDIT.
Looking at the FlatList react-native Docs, Flatlist returns an object looking like :
{item, index, separators}
Where item is the item you need want to render.
So you need to either use :
renderItem={({item }) => <Itm title={lst.title} />} //must be item
or
renderItem={({item: lst}) => <Itm title={lst.title} />}
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