Skip to content

Instantly share code, notes, and snippets.

@inflrscns
Created June 2, 2022 03:19
Show Gist options
  • Save inflrscns/fa5f3d4551947cbf4735ac8373d9bbef to your computer and use it in GitHub Desktop.
Save inflrscns/fa5f3d4551947cbf4735ac8373d9bbef to your computer and use it in GitHub Desktop.
MUI Data Grid Premium single grouped row selection
import React, { useState } from 'react';
import { DataGridPremium, useGridApiRef, useKeepGroupedColumnsHidden } from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
const TableTest = () => {
const [selectionModel, setSelectionModel] = useState([]);
const data = useMovieData();
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['company'],
},
},
});
return (
<DataGridPremium
{...data}
autoHeight
checkboxSelection
disableSelectionOnClick
apiRef={apiRef}
rowGroupingColumnMode="single"
initialState={initialState}
selectionModel={selectionModel}
onSelectionModelChange={selectedItems => {
if(selectedItems.length === 0) {
setSelectionModel([]);
}
if(selectedItems.length < selectionModel.length) {
let removedItems = selectionModel.filter(itm => !selectedItems.includes(itm));
removedItems.map(id => {
if(`${id}`.indexOf('auto-generated-row-') === 0) {
// deselect group children
let children = apiRef.current.getRowGroupChildren({groupId: id});
selectedItems = selectedItems.filter(itm => !children.includes(itm));
} else {
// deselect parent
let groupingColumn = apiRef.current.state.rowGrouping.model[0];
if(apiRef.current.getRow(id)) {
let childValue = apiRef.current.getRow(id)[groupingColumn];
selectedItems = selectedItems.filter(itm => itm !== `auto-generated-row-${groupingColumn}/${childValue}`);
}
}
})
} else {
selectedItems = selectedItems.flatMap(id => {
if(`${id}`.indexOf('auto-generated-row-') === 0) {
// select row group children
let children = apiRef.current.getRowGroupChildren({groupId: id});
return [...children, id];
} else {
return id;
}
})
}
// Set() removes duplicate rows
setSelectionModel([...new Set(selectedItems)])
}}
/>
);
}
export default TableTest;
@inflrscns
Copy link
Author

@jarrisoncano you are absolutely right I forgot to add that part. Unfortunately my project no longer needs this functionality so I haven't had time to do any updates to this. If you figure out a solution let me know though!

@jarrisondev
Copy link

i just find a method in the documentiation for filter the childrens that match with the currentFilters

image

https://mui.com/x/react-data-grid/row-grouping/#get-the-rows-in-a-group

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment