Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
johhansantana opened this issue Sep 15, 2017 · 32 comments
Labels

Comments

@johhansantana
Copy link

I'm trying to figure out how can I get unique keys for each record.

So far, my code looks like this:

let lastIndex = 0
const updateIndex = () => {
  lastIndex++
  return lastIndex
}

...

constructor() {
  super()

  this.state = {
    columns: [ {
      title: 'Nombre',
      dataIndex: 'name',
      key: `name${updateIndex()}`
    }, {
      title: 'Precio',
      dataIndex: 'price',
      key: `price${updateIndex()}`
    }, {
      title: 'Precio regular',
      dataIndex: 'regularPrice',
      key: `regularPrice${updateIndex()}`
    }, {
      title: 'Categoría(s)',
      key: `id${updateIndex()}`,
      render: (text, record) => (
        <span>
          {
            record.categories.map((r, index) => (
              <span key={index}>
                {
                  index > 0 &&
                  <span className="ant-divider"/>
                }
                <span>{r.name}</span>
              </span>
            ))
          }
        </span>
      )
    }, {
      title: 'Action',
      key: `id${updateIndex()}`,
      render: (text, record) => (
        <span>
          <a href="#">Editar - {record.name}</a>
          <span className="ant-divider"/>
          <a href="#" style={{color: 'red'}}>Borrar</a>
        </span>
      )
    }, ]
  }
}

But I'm still getting the error that each record in table should have a unique key.

What would be the best way to achieve this?

@ant-design-bot
Copy link
Contributor

Hello @johhansantana, your issue has been closed because it does not conform to our issue requirements. Please use the Issue Helper to create an issue, thank you!

@afc163
Copy link
Member

afc163 commented Sep 15, 2017

That means the key of your data, not columns.

@ahmetkuslular
Copy link

I have the same problem. How can we solve this? @ant-design-bot @afc163

@funnyleolee
Copy link

With columns if not set dataIndex property, column key should be set unique key.

@johhansantana key not unique ↓

title: 'Categoría(s)',
key: `id${updateIndex()}`,
...
title: 'Action',
key: `id${updateIndex()}`,

@buvinghausen
Copy link

buvinghausen commented Jan 8, 2018

@ahmetkuslular The error message is pretty explicit your data set must contain items with a key property on them or you must specify the rowKey property on the Table component with the name from a field in your dataset which is unique to each row.

Source Code Here

<Table 
  columns={columns} 
  dataSource={this.props.categories} 
  rowKey="name" 
/>

@jdhiro
Copy link

jdhiro commented Jul 9, 2018

This one was confusing to me as well, because I was confusing COLUMN keys with ROW keys. This error has nothing to do with "key" in your column config.

Ant is expecting you to have a unique key specifically named "key" on each row of data, like so:

{ key: 1, value: 'foo'}

My data had "id" instead:

{ id: 1, value: 'foo'}

In order to resolve this, I added a rowKey property to my Table like so:

<Table columns={this.columns} dataSource={this.state.results} rowKey='id' />

@joshpitzalis
Copy link

<Table .... rowKey={record => record.countryId} ... /> fixed it for me.
countryId being a unique values on each item field in your data.

@autumnblue
Copy link

In Ant-design table, rowKey props type is string.
So I added it as string using uuid. so I resolved error.

@storesbuzz
Copy link

storesbuzz commented Sep 24, 2019

Hey guys, adding rowKey to Table solved my issue
<Table rowKey="id" ...../>

and 'id' is key of one of the column inside table as -
const columns = [
{
title: '#',
dataIndex: data.id,
key: 'id',
},
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
.
.
yeah and my id is a unique string too. By this change, I can see columns have an id set as 'data-row-key' property for each column and no warning now.

@xgqfrms
Copy link

xgqfrms commented Oct 22, 2019

solution 1

each col has on 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 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

@keithort
Copy link

@xgqfrms, in solution 2, you can shorten the rowKey prop to rowkey="id". It works the same.

@kfrajtak
Copy link

What I am getting is this message

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `TableRow`. See https://fb.me/react-warning-keys for more information.
    in TableCell (created by TableRow)
    in TableRow (created by Connect(TableRow))
    in Connect(TableRow) (created by ExpandableRow)

indicating that the problem in the TableCell, but how can I set the key prop there?

I have noticed the examples on Antd page are not throwing this error.

Thanks for help.

@tuanalumi
Copy link

tuanalumi commented Dec 17, 2019

What I am getting is this message

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `TableRow`. See https://fb.me/react-warning-keys for more information.
    in TableCell (created by TableRow)
    in TableRow (created by Connect(TableRow))
    in Connect(TableRow) (created by ExpandableRow)

Hey, I've just figured it out. In columns prop, you need to have either dataIndex or key.

It is mentioned in this section: https://ant.design/components/table/#Column

@kfrajtak
Copy link

@tuanalumi, thanks for pointing that out, I have added key and I am no longer getting that warning!

@amermemic
Copy link

This one was confusing to me as well, because I was confusing COLUMN keys with ROW keys. This error has nothing to do with "key" in your column config.

Ant is expecting you to have a unique key specifically named "key" on each row of data, like so:

{ key: 1, value: 'foo'}

My data had "id" instead:

{ id: 1, value: 'foo'}

In order to resolve this, I added a rowKey property to my Table like so:

<Table columns={this.columns} dataSource={this.state.results} rowKey='id' />

fixed it for me, thanks

@panda6412
Copy link

What if I want to set rowKey with index in antd V4

@deschantkn
Copy link

@ahmetkuslular The error message is pretty explicit your data set must contain items with a key property on them or you must specify the rowKey property on the Table component with the name from a field in your dataset which is unique to each row.

Source Code Here

<Table 
  columns={columns} 
  dataSource={this.props.categories} 
  rowKey="name" 
/>

Worked like a charm, thank you!

@tharindu-ascentic
Copy link

@ahmetkuslular The error message is pretty explicit your data set must contain items with a key property on them or you must specify the rowKey property on the Table component with the name from a field in your dataset which is unique to each row.

Source Code Here

<Table 
  columns={columns} 
  dataSource={this.props.categories} 
  rowKey="name" 
/>

Awesome :) Thank You <3

@Mark910413
Copy link

being a unique values on each item field in your data.

Don't work for me

@reneolivo
Copy link

Weirdly enough I got this error because I tried to wrap <Table.ColumnGroup> and <Table.Column> in a component that would print the necessary tags by passing an object. Ant Design, as always, hated the idea of me using my own components to wrap theirs (which I think it's a pattern I have found with Ant Design).

So instead of doing this:

<Table {...tableProps}>
  <TableColumns columns={columns} /> {/* prints all column groups and columns */}
</table>

I had to do this:

<Table {...tableProps}>
  {getTableColumns(columns)}
</table>

Not working with custom components is bad, but also printing that there's something wrong with the key is terrible as well because I spent hours trying to fix my data source, column keys, etc. And they were absolutely fine :\ Not a very descriptive error.

@rickvian
Copy link
Contributor

what if my data doesn't have unique key data?

@ihimrao
Copy link

ihimrao commented Dec 31, 2021

what if my data doesn't have unique key data?

just put a random id for each or use index value.

@cit-gif
Copy link

cit-gif commented Jan 18, 2022

if your data doesn't have an id yet. you can try
import uuid from 'react-uuid';
....
<Table rowKey={() => uuid()} columns={columns} dataSource={data} />

@luckymore
Copy link
Contributor

@cit-gif @autumnblue when using rowSelection mode, will meet a bug that can't select any row😭

if your data doesn't have an id yet. you can try import uuid from 'react-uuid'; .... <Table rowKey={() => uuid()} columns={columns} dataSource={data} />

@cit-gif
Copy link

cit-gif commented Jun 2, 2022

@cit-gif @autumnblue when using rowSelection mode, will meet a bug that can't select any row😭

if your data doesn't have an id yet. you can try import uuid from 'react-uuid'; .... <Table rowKey={() => uuid()} columns={columns} dataSource={data} />

@luckymore you can see my code example : https://codesandbox.io/s/selection-and-operation-antd-4-20-7-forked-evqw0o?file=/demo.js

@luckymore
Copy link
Contributor

@cit-gif you didn't set the rowKey property, I have a demo here

rowKey={() => Math.random()}

@duyhung85
Copy link

@luckymore I tried on tree data table and its not working:
https://codesandbox.io/s/tree-data-antd-4-21-0-forked-305wyd?file=/demo.js
It add dynamic key to the parent only, all the children data is gone. Is this a bug? or any way I can make dynamic key working with tree data table?
Thanks,

@cit-gif
Copy link

cit-gif commented Jun 7, 2022

@luckymore if you use key in object then you don't need rowKey
image

@luckymore
Copy link
Contributor

luckymore commented Jul 20, 2022

@duyhung85 Just like @cit-gif said, I make a mistake.... you should set the key in dataSource.

@ValeronS
Copy link

ValeronS commented Nov 9, 2022

in Vue 3:

<a-table
    ...
    :columns="yourColumns"
    :data-source="yourData"
    // the solution:
    :row-key="record => record.id"
    // or
    :rowKey="record => record.id"
  >

@vitalijalbu
Copy link

what if my api has no ids? i mean all data may have same value

@rickvian
Copy link
Contributor

rickvian commented May 27, 2023

@vitalijalbu you may want to generate the ID on the fly

try to figure out first:

  • can i ask for unique ID from Backend?
  • can i generate guaranteed unique ID based on multiple field (composite key)? such as fullname+address+{other data}
  • if not, then you have to generate your own index number into the dataset, or uuid
import uuid from 'react-uuid';
<Table	 rowKey={() => uuid()} columns={columns} dataSource={data} />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests