Since selection is not a built-in feature, you can implement it by creating a wrapper component (e.g., SelectableTable) that manages selectedRowKeys in its internal state.
To implement selection, follow these steps:
- Manage State: Maintain an array of
selectedRowKeys in your component state. If the table is uncontrolled, use defaultSelectedRowKeys to initialize it. - Create a Selection Column: Add a special column at the beginning of your
columns array. This column should use a custom cellRenderer (like a checkbox) that calls an onChange handler. - Handle Changes: In the
onChange handler, update the selectedRowKeys state by adding or removing the row's key based on the interaction. - Visual Feedback: Use the
rowClassName prop to apply a CSS class (e.g., .row-selected) to rows whose keys are present in selectedRowKeys. - Cleanup: Use a method like
removeRowKeysFromState to purge keys from the internal state when rows are deleted to prevent stale selection data.
const StyledTable = styled(BaseTable)`
.row-selected {
background-color: #e3e3e3;
}
`;
class SelectionCell extends React.PureComponent {
_handleChange = e => {
const { rowData, rowIndex, column } = this.props;
const { onChange } = column;
onChange({ selected: e.target.checked, rowData, rowIndex });
};
render() {
const { rowData, column } = this.props;
const { selectedRowKeys, rowKey } = column;
const checked = selectedRowKeys.includes(rowData[rowKey]);
return <input type="checkbox" checked={checked} onChange={this._handleChange} />;
}
}
class SelectableTable extends React.PureComponent {
// ... implementation details for managing selectedRowKeys and rowClassName ...
render() {
const { columns, children, selectable, selectionColumnProps, ...rest } = this.props;
const { selectedRowKeys } = this.state;
let _columns = columns || normalizeColumns(children);
if (selectable) {
const selectionColumn = {
width: 40,
flexShrink: 0,
resizable: false,
frozen: Column.FrozenDirection.LEFT,
cellRenderer: SelectionCell,
...selectionColumnProps,
key: '__selection__',
rowKey: this.props.rowKey,
selectedRowKeys: selectedRowKeys,
onChange: this._handleSelectChange,
};
_columns = [selectionColumn, ..._columns];
}
return <StyledTable {...rest} columns={_columns} rowClassName={this._rowClassName} />;
}
}