1
votes

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?

1
You should put a key on every element that is part of an array, i.e. th, td, tr in this case.Tholle
@root_access did you resolve your issue? If so - you can contribute as answering / accepting an answer / or giving some details. Otherwise - all the efforts were on vain!Jordan Enev

1 Answers

2
votes

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