Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array index on FlatList in React Native

I have an array of objects as follows. None of the objects has a unique key.

[
   {
       data1: "text1",
       data2: "text2"
   },
   {
       data1: "text3",
       data2: "text4"
   }
]

I have a FlatList defined as follows:

<FlatList

     data={this.state.items}
     renderItem={this.renderItem}
/>

I have also tried adding:

 keyExtractor={this._keyExtractor}

but I still get the same message. I am not sure what the above this._keyExtractor is supposed to be doing. Is it a built in function to pull the index or a function that I am supposed to create myself?

What am I doing wrong and how can I just use the array index as my unique key?

like image 902
kojow7 Avatar asked Feb 10 '26 08:02

kojow7


2 Answers

keyExtractor already calculates the array indices for the data that you provide to it.

Therefore if you want to use array indices as the unique element then you can do

<FlatList 
      data={this.state.items}
      renderItem={this.renderItem} //... toString() since it accepts string elements
      keyExtractor={(item, index) => index.toString()}
 />
like image 167
Pritish Vaidya Avatar answered Feb 13 '26 11:02

Pritish Vaidya


I believe you copy keyExtractor={this._keyExtractor} from ReactNative website. You forgot to copy the function to your file.

_keyExtractor = (item, index) => item.id;

Or you just copy the function and paste in keyExtrator

<FlatList
    data={this.state.items}
    renderItem={this.renderItem}
    keyExtractor={(item, index) => item.id}
/>
like image 33
Alan Yong Avatar answered Feb 13 '26 13:02

Alan Yong



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!