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

LoneWolfPR picture LoneWolfPR · Dec 16, 2016 · Viewed 11.3k times · Source

I'm getting that error, but I'm defining a key. Here's my App.js that it's complaining about.

import React from 'react';
import Relay from 'react-relay';
import AccountTable from './AccountTable';

class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Account list</h1>
          {this.props.viewer.accounts.edges.map(edge =>
            <AccountTable key={edge.node.id} account={edge.node} />
          )}
      </div>
    );
  }
}

export default Relay.createContainer(App, {
    fragments: {
        viewer: () => Relay.QL`
            fragment on User {
                accounts(first: 10) {
                    edges {
                        node {
                            ${AccountTable.getFragment('account')}
                        }
                    }
                }
            }
        `,
    },
});

Answer

Davin Tryon picture Davin Tryon · Dec 16, 2016

The easiest way to correct this is to base the key off the index of the map:

{this.props.viewer.accounts.edges.map((edge, i) =>
    <AccountTable key={i} account={edge.node} />
)}

Then, you don't have to worry about how unique the value of edge.node.id is. The key only needs to be unique in the context of all the AccountTable siblings. It doesn't need to be globally unique. So, the index works well.

However, if you have a stable id that is based off of the object, that is obviously better.