user9062626
user9062626

Reputation:

Persistent Warning: "Each child in an array or iterator should have a unique 'key' prop" even if key is already set

I've been trying to figure about the warning that react had been showing. Clearly I have the tags set with key yet the warning still insists.

render() {
    return (
        <div className="table">
            <table>
                <tbody>
                    {Object.entries(this.props.rowData).map(rowData => 
                        <tr key={rowData.id}> 
                            {Object.entries(rowData).map((data, index) =>
                                <td key={index}> Test </td>
                            )}
                        </tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}

Upvotes: 1

Views: 89

Answers (1)

nem035
nem035

Reputation: 35491

It seems that you are misunderstanding what Object.entries does.

Object.entries returns an array of tuples (array of 2 elements) for each key/value pair it contains:

// logs [["id", 5], ["name", "example"]]
console.log(
  Object.entries(
    { id: 5, name: 'example' }
  )
)

What you probably want is Object.values which will return an array of values from an object.

// logs [5, 'example']
console.log(
  Object.values(
    { id: 5, name: 'example' }
  )
)

EDIT:

Based on the data you provided, rowData is an array so there's no need to use any Object.* methods on it. We can just map on it directly:

render() {
    return (
        <div className="table">
            <table>
                <tbody>
                    {this.props.rowData.map(row => 
                        <tr key={row.id}> 
                            {Object.entries(row).map(([key,value], index) =>
                                <td key={index}> {key},{value} </td>
                            )}
                        </tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}

Upvotes: 3

Related Questions