Search code examples
javascriptreactjsdatatableantdant-design-pro

Select just one row in ant-design table component


i'm having a problem and need some help. We are using ant-design library in our project. https://ant.design/components/table The component we should use is a table. When i click on a row i must trigger an action. However i must check only one row not many so when i click on a row the checkbox in the previous row should be deselect.

My code is here:

onSelectChange = selectedRowKeys => {
    if (selectedRowKeys.length > 1) {
      const lastSelectedRowIndex = [...selectedRowKeys].pop();
      this.setState({ selectedRowKeys: lastSelectedRowIndex });
    }
    this.setState({ selectedRowKeys });
    console.log('selectedRowKeys changed: ', selectedRowKeys);
  };

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <React.Fragment>
        <div style={{ marginBottom: 16 }} />
        <Table
          rowSelection={rowSelection}
          columns={columnEvaluation}
          dataSource={result}
        />
      </React.Fragment>
    );
  }

The selectedRow array is having the latest value BUT But the checkbox is NOT checked. Any ideas?


Solution

  • Checkboxes are used to let a user select one or more options of a limited number of choices, and Radio buttons let a user select only one of a limited number of choices.

    pass a type to your table's rowSelection prop, default is checkbox.

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      type: 'radio'
    };