Created
June 2, 2022 03:19
-
-
Save inflrscns/fa5f3d4551947cbf4735ac8373d9bbef to your computer and use it in GitHub Desktop.
MUI Data Grid Premium single grouped row selection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
i just find a method in the documentiation for filter the childrens that match with the currentFilters
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
@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!