Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot change prop in flatlist renderItem

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
like image 557
Bijaya Avatar asked May 22 '26 03:05

Bijaya


1 Answers

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} />}
like image 70
Auticcat Avatar answered Jun 01 '26 16:06

Auticcat