6

I'm trying to grab the single element key in the table. But I get undefined How can I grab the id?

https://ant.design/components/table/#components-table-demo-expand-children

const [select, setSelect] = useState({
    selectedRowKeys: [],
    loading: false,
  });

console.log("selectedRowKeys", select);

const { selectedRowKeys, loading } = select;

const rowSelection = {
selectedRowKeys,
onChange: (selectedRowKeys) => {
  setSelect({
    ...select,
    selectedRowKeys: [...select.selectedRowKeys, selectedRowKeys],
  });
},
};

return (
<div>
  <Table
    columns={columns}
    rowSelection={rowSelection}
    dataSource={dataSource}
    loading={!props.employeeList}
  />
</div>);

Here's a screenshot of console.log()

Shreyas Chorge
  • 127
  • 1
  • 6

1 Answers1

8

You need to add a key prop on each object of dataSource array

const dataSource = [
  {
    key: 1,
    name: `Edward King 1`,
    age: 32,
    address: `London, Park Lane no. 1`
  },
  {
    key: 2,
    name: `Edward King 2`,
    age: 35,
    address: `London, Park Lane no. 2`
  }
];

then in your rowSelection object you need remove this code [...select.selectedRowKeys, selectedRowKeys], this will push to state if you deselect an item and select it again and result to duplications. It should be:

const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys) => {
      setSelect({
        ...select,
        selectedRowKeys: selectedRowKeys
      });
    }
};

see your working code here

Chanandrei
  • 2,211
  • 3
  • 10
  • 19