Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')}
                        }
                    }
                }
            }
        `,
    },
});
like image 983
LoneWolfPR Avatar asked Dec 16 '16 16:12

LoneWolfPR


1 Answers

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.

like image 129
Davin Tryon Avatar answered Oct 03 '22 18:10

Davin Tryon