Aashay Amballi
Aashay Amballi

Reputation: 1411

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}/>

Upvotes: 2

Views: 25821

Answers (2)

gwynplaine
gwynplaine

Reputation: 1

The author above said all the right things, I decided to share my experience. I have an array of objects with no key field (hello backend). Initially I filtered this array by a condition (depends on your task), for example, that the coin_symbol field === "WBNB". After filtering, I immediately use map to create a new array. Don't forget to make local state.

const [selectedRowKeys, setSelectedRowKeys] = useState()
setSelectedRowKeys(dashboardData?.filter(i => i.coin_symbol === 'WBNB').map(i => i.id))

Then, after digging in the table props, I saw a props defaultSelectedRowKeys, which takes an array. Further everything is simple - to this props assign value to our new array.

const rowSelection = { defaultSelectedRowKeys: selectedRowKeys, ...otherProps (like onChange, getCheckboxProps, etc.)

Another important thing - if you have, as I do, the data from the server go long, better not render a table, but rather, for example, some kind of loading text or a slider.

selectedRowKeys ? <YourTable dataSource={yourData} rowSelection={rowSelection}/> : <Loader/>

I hope it helps someone! (~ ̄▽ ̄)~

Upvotes: 0

Trần C&#244;ng
Trần C&#244;ng

Reputation: 298

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>
    );
  }
}

Upvotes: 5

Related Questions