DEV Community

Cover image for VirtualizedList: missing keys for items
bob.ts
bob.ts

Posted on

VirtualizedList: missing keys for items

VirtualizedList: missing keys for items, make sure to specify a key property on each item or provide a custom keyExtractor.

This error message plagued me for a few minutes. The solutions I looked at delved into creating a custom keyExtractor. I'll show that solution later; what I found was that I was missing one part in the declaration of my renderItem function.

The Code

// The function to render
renderItem = (item) => { };

// Usage within render
<FlatList data={data} renderItem={this.renderItem} />
Enter fullscreen mode Exit fullscreen mode

The Solution

This is the solution that ultimately worked for me; there was another solution that will show later that I think would have worked and would have masked the true issue.

The solution is actually in the parameter definition of the "function to render" above. I changed the code, as follows ...

// The function to render
renderItem = ({ item, index }) => { };
Enter fullscreen mode Exit fullscreen mode

No other code changed. The error message listed above went away.

The Alternate Solution

The keyExtractor solution looks like this ...

You need a keyExtractor parameter. By default it will check to see if the item has a key property (which you don't that why you are getting this message).

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item.key, then falls back to using the index, like React does.

Do this:

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

<FlatList data={this.state.list} renderItem={this.renderItem}
   keyExtractor={this._keyExtractor} />
Enter fullscreen mode Exit fullscreen mode

Summary

The first solution fixed my issue. The second solution would have gotten rid of the error message, but I believe it is MUCH more complicated and can hide what is truly going on in the code.

Top comments (0)