Reputation: 41
I want to be able to select multiple rows at a time from a react-virtualized table, either with click-and-drag, or holding shift to select from one index to another. I know there is a onRowClick method, and I am currently using it for the single row selection, but it's not enough. Is there a simple way to do this?
Upvotes: 2
Views: 1513
Reputation: 41
I actually found an answer on a related thread. I checked in the event from the onRowClick method if the shiftKey was pressed and implemented my own selection. I add the rows from the data to the selectedRows. 'data' comes from props. The code is below, hope it helps.
const [previousSelectedRow, setPreviousSelectedRow] = useState();
const [selectedRows, setSelectedRows] = useState();
const handleRowClick = (info) => {
let localSelectedRows = [];
if (info.event.shiftKey && previousSelectedRow) {
const previousSelectedRowIndex = data.findIndex(rowData => rowData.index = previousSelectedRow.index);
const currentSelectedRowIndex = data.findIndex(rowData => rowData.index = info.index);
if (previousSelectedRowIndex < currentSelectedRowIndex) {
for (let i = previousSelectedRowIndex; i < currentSelectedRowIndex; i++) {
localSelectedRows.push(data[i);
}
} else {
for (let i = currentSelectedRowIndex; i < previousSelectedRowIndex; i++) {
localSelectedRows.push(data[i]);
}
}
} else {
setPreviousSelectedRow(info);
localSelectedRows.push(info.rowData);
}
setSelectedRows(localSelectedRows);
}
Upvotes: 1
Reputation:
First you can add check box in start of every row to keep tack of selected rows And then you can select multiple rows at a time by calling below function onClick of checkbox.
const checkedData = []
const selectRows = (obj) => {
const already = checkedData.some(item => item.id === obj.id)
if (already) {
const index = checkedData.findIndex(item => item.id === obj.id)
checkedData.splice(index, 1)
} else {
checkedData.push(obj)
}
}
In this way you can also pop the particular row from array by clicking on that row again or by unCheck the check bok.
Upvotes: 3