Search code examples
reactjsantd

Select the table rows by default based on the data in antd table


I'm new to antd and I'm stuck at one place in my project. I want to check/select the checkboxes of rows by default based on the sourcedata or data.

for example if i have the datasource as

const data =
[ 
{
key: "1",
name: "John",
age: 22,
chosen: true,
working: null
},
{
key : "2",
name: "Jason",
age: 23,
chosen: false,
working: 'John'
}]

So based on datasource if any object has chosen key as true, I want to check/select the checkbox of those rows by default.

I can filter out the data array depending on the chosen key has the value true or not. But how to check the checkbox by default? Is there any prop for the antd table, which will take the array of filtered data and check/select the checkbox for those rows?

I tried to check the rows using checked attribute inside getCheckboxProps but when I use that in console I get a warning saying "Warning: [antd: Table] Do not set checked or defaultChecked in getCheckboxProps. Please use selectedRowKeys instead."

Below is the code which I'm currently using.

const data =
[ 
 {
  key: "1",
  name : "John",
  age : 22,
  chosen: true,
  working: null
 },
 {
  key : "2",
  name: "Jason",
  age: 23,
  chosen: false,
  working: "John"
 }
]

const fiterSelectedRows = data.filter(row => {
        return row.chosen;
});

const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(
                `selectedRowKeys: ${selectedRowKeys}`,
                "selectedRows: ",
                selectedRows
            );
        },
        getCheckboxProps: record => {
            return {
                disabled: record.working != null,
                name: record.working
            };
        }
};

<Table rowSelection={rowSelection} columns={columns} dataSource={data}/>

Solution

  • Notice selectedRowKeys: data.filter(item => item.chosen).map(item => item.key). selectedRowKeys contain all keys of items, all items have keys in here will be checked by default.

    You need to get all items that have chosen is true.

    data.filter(item => item.chosen)
    // [{key: '1', name: 'John Brown', ...},
    //  {key: '3', name: 'Joe Black', ...},
    //  {key: '4', name: 'Joe Black', ...}]
    // all items have chosen is true
    

    Then get all keys of this array.

    data.filter(item => item.chosen).map(item => item.key)
    // ['1', '2', '3']
    // all keys of items have chosen is true
    

    Exmample code:

    Data

    const data = [{
      key: '1',
      name: 'John Brown',
      age: 32,
      chosen: true,
      address: 'New York No. 1 Lake Park',
    }, {
      key: '2',
      name: 'Jim Green',
      age: 42,
      chosen: false,
      address: 'London No. 1 Lake Park',
    }, {
      key: '3',
      name: 'Joe Black',
      age: 32,
      chosen: true,
      address: 'Sidney No. 1 Lake Park',
    }, {
      key: '4',
      name: 'Disabled User',
      age: 99,
      chosen: true,
      address: 'Sidney No. 1 Lake Park',
    }];
    

    Datatable

    class App extends React.Component {
      state = {
        selectedRowKeys: data.filter(item => item.chosen).map(item => item.key), // Check here to configure the default column
        loading: false,
      };
    
      start = () => {
        this.setState({ loading: true });
        // ajax request after empty completing
        setTimeout(() => {
          this.setState({
            selectedRowKeys: [],
            loading: false,
          });
        }, 1000);
      };
    
      onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
      };
    
      render() {
        const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
          selectedRowKeys,
          onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Button type="primary" onClick={this.start} disabled={!hasSelected} loading={loading}>
                Reload
              </Button>
              <span style={{ marginLeft: 8 }}>
                {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
              </span>
            </div>
            <Table rowSelection={rowSelection} columns={columns} dataSource={data} />
          </div>
        );
      }
    }