Reputation: 25526
in MUI paid version there is a checkboxSelectionVisibleOnly
prop.
How to achieve the same with the community/free version?
I am using v6
.
This is what I have so far, but when I select single row it selects all rows.
The goal is to select All Rows on current page only
If I'm on another page it should add rows to the currently selected ones
onRowSelectionModelChange={(rowSelectionModel) => {
// user cleared selection
if (rowSelectionModel.length === 0) {
return setSelectedRows([]);
}
const {
state: {
rowSelection,
pagination: {
paginationModel: { page, pageSize },
},
},
} = apiRef.current;
// user unchecked row
if (rowSelectionModel.length < rowSelection.length) {
return setSelectedRows(rowSelectionModel);
}
const startIndex = page * pageSize;
const endIndex = startIndex + pageSize;
const currentPageRows = apiRef.current
.getAllRowIds()
.slice(startIndex, endIndex);
// no selection yet, select rows from current page
if (rowSelection.length === 0) {
// limit selection to current page rather than ALL table entries
return setSelectedRows(currentPageRows);
}
const currentSelection = new Set(rowSelection);
// user selected single row, maybe on another page?
currentPageRows.forEach((row) => {
if (currentSelection.has(row)) {
currentSelection.delete(row);
} else {
currentSelection.add(row);
}
});
return setSelectedRows(Array.from(currentSelection));
}}```
Upvotes: 1
Views: 938
Reputation: 25526
export const checkboxSelectionVisibleOnly = ({
apiRef,
rowSelectionModel,
}: {
apiRef: GridApi;
rowSelectionModel: GridRowSelectionModel;
}): GridRowSelectionModel => {
const {
state: {
rowSelection,
pagination: {
paginationModel: { page, pageSize },
},
},
} = apiRef;
// no selection yet, select rows from current page
if (rowSelection.length === 0) {
// user clicked on "All" checkbox
if (rowSelectionModel.length > 1) {
const startIndex = page * pageSize;
const endIndex = startIndex + pageSize;
return apiRef.getAllRowIds().slice(startIndex, endIndex);
} else {
// user clicked on specific row
return rowSelectionModel;
}
}
// user unchecked row(s)
if (rowSelectionModel.length < rowSelection.length) {
return rowSelectionModel;
}
return rowSelectionModel;
};
Upvotes: 1