Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key

Tags:

reactjs

antd

I am rendering a table with ant design and it works fine, but there is a warning in the console:

Each record in table should have a unique key prop,or set rowKey to an unique primary key

My code is as follows:

import React, { Component } from 'react';
import {  Table} from 'antd';
import { adalApiFetch } from '../../adalConfig';


class ListTenants extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }



    fetchData = () => {
        adalApiFetch(fetch, "/Tenant", {})
          .then(response => response.json())
          .then(responseJson => {
            if (!this.isCancelled) {
                const results= responseJson.map(row => ({
                    ClientId: row.ClientId,
                    ClientSecret: row.ClientSecret,
                    Id: row.Id,
                    SiteCollectionTestUrl: row.SiteCollectionTestUrl,
                    TenantDomainUrl: row.TenantDomainUrl
                  }))
              this.setState({ data: results });
            }
          })
          .catch(error => {
            console.error(error);
          });
      };


    componentDidMount(){
        this.fetchData();
    }

    render() {
        const columns = [
                {
                    title: 'Client Id',
                    dataIndex: 'ClientId',
                    key: 'ClientId'
                }, 
                {
                    title: 'Site Collection TestUrl',
                    dataIndex: 'SiteCollectionTestUrl',
                    key: 'SiteCollectionTestUrl',
                },
                {
                    title: 'Tenant DomainUrl',
                    dataIndex: 'TenantDomainUrl',
                    key: 'TenantDomainUrl',
                }
        ];



        return (
            <Table columns={columns} dataSource={this.state.data} />
        );
    }
}

export default ListTenants;
like image 368
Luis Valencia Avatar asked Aug 06 '18 08:08

Luis Valencia


4 Answers

React renders lists using the key prop. It works so because react allows you to reduce the complexity of diffing algorithms and reduce the number of DOM mutations. You can read a bit more in react reconciliation docs: https://reactjs.org/docs/reconciliation.html

In your case, you added the keys to the columns, but not for rows. Add the key field to the data source. So your code could be the following:

import React, { Component } from 'react';
import {  Table} from 'antd';
import { adalApiFetch } from '../../adalConfig';


class ListTenants extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }



    fetchData = () => {
        adalApiFetch(fetch, "/Tenant", {})
          .then(response => response.json())
          .then(responseJson => {
            if (!this.isCancelled) {
                const results= responseJson.map(row => ({
                    key: row.id, // I added this line
                    ClientId: row.ClientId,
                    ClientSecret: row.ClientSecret,
                    Id: row.Id,
                    SiteCollectionTestUrl: row.SiteCollectionTestUrl,
                    TenantDomainUrl: row.TenantDomainUrl
                  }))
              this.setState({ data: results });
            }
          })
          .catch(error => {
            console.error(error);
          });
      };


    componentDidMount(){
        this.fetchData();
    }

    render() {
        const columns = [
                {
                    title: 'Client Id',
                    dataIndex: 'ClientId',
                    key: 'ClientId'
                }, 
                {
                    title: 'Site Collection TestUrl',
                    dataIndex: 'SiteCollectionTestUrl',
                    key: 'SiteCollectionTestUrl',
                },
                {
                    title: 'Tenant DomainUrl',
                    dataIndex: 'TenantDomainUrl',
                    key: 'TenantDomainUrl',
                }
        ];



        return (
            <Table columns={columns} dataSource={this.state.data} />
        );
    }
}

export default ListTenants;
like image 36
Nik Avatar answered Sep 21 '22 22:09

Nik


Just add a unique key value in tag link this:

   <Table
   columns={columns}
   dataSource={this.state.data} 
   rowKey="Id" />  // unique key

Hope this help

like image 153
Jhon Avatar answered Sep 19 '22 22:09

Jhon


React Table unique key / rowKey

Each record in table should have a unique key prop,or set rowKey to an unique primary key.

solution 1

each col has a unique key

// each column with unique key

import React from 'react';

import {
  Table,
} from 'antd';

const leftTableColumns = [
  {
    title: 'Page / Modal',
    dataIndex: 'pageModal',
    key: 'pageModal',
  },
  {
    title: 'Success Rate',
    dataIndex: 'successRate',
    key: 'successRate',
  },
];

const LeftTable = (props) => {
  const {
    leftTableDatas,
  } = props;
  return (
    <>
      <Table
        columns={leftTableColumns}
        dataSource={leftTableDatas}
      />
    </>
  );
};

export {
  LeftTable,
};

export default LeftTable;


solution 2

only need set rowkey on the table with the unique value

// table with rowkey

import React from 'react';

import {
  Table,
} from 'antd';

const leftTableColumns = [
  {
    title: 'Page / Modal',
    dataIndex: 'pageModal',
  },
  {
    title: 'Success Rate',
    dataIndex: 'successRate',
  },
];

const LeftTable = (props) => {
  const {
    leftTableDatas,
  } = props;
  return (
    <>
      <Table
        // shorthand rowKey
        rowKey="id"
        // rowKey={obj => obj.id}
        columns={leftTableColumns}
        dataSource={leftTableDatas}
      />
    </>
  );
};

export {
  LeftTable,
};

export default LeftTable;


ref

https://ant.design/components/table/

image

like image 39
xgqfrms Avatar answered Sep 21 '22 22:09

xgqfrms


Because you are not adding key to dataSource array, add a key in that also.

Like this:

const results= responseJson.map(row => ({

    key: row.ClientId,     // here

    ClientId: row.ClientId,
    ClientSecret: row.ClientSecret,
    Id: row.Id,
    SiteCollectionTestUrl: row.SiteCollectionTestUrl,
    TenantDomainUrl: row.TenantDomainUrl
}))

Or you can use any unique value of dataSource array as key by using property rowKey, like this:

<Table
   columns={columns}
   dataSource={this.state.data}

   rowKey="Id" />     // any unique value

Doc Reference.

like image 44
Mayank Shukla Avatar answered Sep 23 '22 22:09

Mayank Shukla