Search code examples
reactjsantd

Why is rowselect of antd-react selecting all the rows when I click only one row in my table?


I have a table built with antd in react. I am getting the data from an API endpoint. Everything else works fine. But when i click one row at the table, all the rows are getting selected. The row selection is working fine with constant data of antd documentation. But when i plug it in my code with dynamic data rendering it just goes crazy and selects every row whenever I click on only one row. Here is my state :

class TabularView extends React.Component {

   intervalID;


   state = {
        selectedRowKeys: [], 
        loading: false,
        data: [],
        columns : [],
        length : '',
        approve : '',
        perc : '',
        icon : <ArrowUpOutlined/>,
        color : '',
        visible: false

         }

Here is my other functions for the row selection

 start = () => {
this.setState({ loading: true });
 setTimeout(() => {
  this.setState({
    selectedRowKeys: [],
    loading: false,
   });
   }, 1000);
   }

  onSelectChange = selectedRowKeys => {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.setState({ selectedRowKeys });
 }

And here is my render part for the rowselection

render(){
 const { loading, selectedRowKeys } = this.state;
const rowSelection = {
  selectedRowKeys,
  onChange: this.onSelectChange,
};
 return(
 <Table rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.data} pagination={{ pageSize: 20 }} />
 )}

Solution

  • Use an unique key prop to each child to avoid this kind of problem

    Each and every react chield or any map function you use. If you do not provide a unique key prop to it. It will give a warning.

    React always understand it's children by the key prop. So as all the key to the table is the same. As you selecting one row, as the key is same it is selecting all the row. Key prop in react is very much useful for dynamic programming using map function. Please read this for more clarification - React Key Prop