Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Can't fix FlatList keys warning

I'm trying to render a FlatList from json fetched from an api, but I keep getting this error:

Warning: Each child in an array or iterator should have a unique "key" prop.
Check the render method of `VirtualizedList`.

Relevant code:

<FlatList
  data={this.props.tunes}
  keyExtractor={(item, index) => item.id}
  renderItem={({item}) => {
    <Item
      key={item.id}
      title={item.title}
      composer={item.composer}
      year={item.year}
    />
  }}
/>

I'm sure there is a simple fix for this, but after a few days of trying different things I haven't found it. Thanks for your help!

like image 838
Thomas Avatar asked Aug 29 '17 20:08

Thomas


1 Answers

Looks like you need to change key to id as you write item.id in keyExtractor and be sure you have id and it's different for each component:

<FlatList
  data={this.props.tunes}
  keyExtractor={(item, index) => item.id}
  renderItem={({item}) => {
    <Item
      id={item.id} //instead of key
      title={item.title}
      composer={item.composer}
      year={item.year}
    />
  }}
/>

Or if you don't have unique key use keyExtractor={(item, index) => index}

like image 154
Andrew Avatar answered Nov 16 '22 11:11

Andrew