root_access
root_access

Reputation: 162

Warning: Each child in an array or iterator should have a unique "key" prop. Keys are already present

I have a React component that accepts an array and renders it as a table using a predefined key.

<TableFromJson data={this.props.results.events} rowKey="eventID" />

TableFromJson.js

    import React, { Component } from 'react';
    import { Table } from 'react-bootstrap';
    import PropTypes from 'prop-types';

    export class TableFromJson extends Component{

        render() {
            if (!this.props.data)
                return(<p>No data</p>);

            const key = this.props.rowKey;
            let columns = Object.keys(this.props.data[0]);
            let headerComponents = columns.map(col => <th>{col}</th>);

            let rowComponents = this.props.data.map((row) =>{
                let tdList = columns.map(col => <td>{row[col]}</td>);
                let htmlRow = <tr key={row[key]}>{tdList}</tr>;
                return htmlRow;
            });

            return (
                <Table bordered hover responsive striped>
                    <thead>
                        <tr>{headerComponents}</tr>
                    </thead>
                    <tbody>{rowComponents}</tbody>
                </Table>
            );
        }
    }

    TableFromJson.propTypes = {
        data: PropTypes.array,
        key: PropTypes.string
    }

This renders a table as show below:

Component with key shown in React Dev Tools

The tr element already contains the key as you can see from the above screenshot from React Dev tools.

I'm getting the key error ("Warning: Each child in an array or iterator should have a unique "key" prop") every time this component is rendered. What am I missing?

Upvotes: 1

Views: 278

Answers (1)

Jordan Enev
Jordan Enev

Reputation: 18664

You should add keys to the children elements as well: th, td, as you already did it for tr.

Upvotes: 2

Related Questions