0

I am trying to display a table which fetches data from a server and displays all the information in it. The code is printing my table header and information of the first object from the fetched API.

Its giving me an error.

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

import React from "react";

export default class MyTable extends React.Component {
  constructor(props) {
    super(props);

    console.log(props);
  }

  createTable = () => {
    let table = [];

    let tableHeader = (
      <thead>
        <tr>
          {this.props.columns.map(column => {
            return <th key={column.name}>{column.name}</th>;
          })}
        </tr>
      </thead>
    );

    let tableRows = [];
    for (
      let i = this.props.pgNo * this.props.maxItems;
      i < i + this.props.maxItems;
      i++
    ) {
      if (i > this.props.users.length) {
        break;
      } else {
        let row = (
          <tr>
            {this.props.columns.map(column => {
              return (
                <td key={column.key}>{this.props.users[i][column.key]}</td>
              );
            })}
          </tr>
        );

        tableRows.push(row);
      }
      let tableBody = <tbody>{tableRows}</tbody>;
      return (
        <table>
          {table}
          {tableHeader}
          {tableBody}
        </table>
      );
    }
  };
  render() {
    return <div className="col-sm-10">{this.createTable()}</div>;
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
Irtaza Rawjani
  • 101
  • 3
  • 13

3 Answers3

2

you gave a key for both th and td but you

forgot to write a key in tr for row variable

1

When rendering an array of React elements, a key on each element is needed for React to know how to update each element.

const list = ["Apple", "Banana", "Orange"]

class Component extends React.Component {
  render() {
    return list.map(item => {
      return (
        <div key={item}>{item}</div>
      )
    })
  }
}

You can read more about it here.

Sebastian Olsen
  • 10,318
  • 9
  • 46
  • 91
0

The problem is most likely that your <tr> elements don't have keys. Try giving them i as a key.

if (i > this.props.users.length) {
    break;
} else {
    let row = (
      <tr> <--- You should have a key prop here

Try using <tr key={i}>

user2073973
  • 564
  • 6
  • 21