1

How can I make all rows expand/collapse programmatically in MUI ReactJS DataGrid?

What have I tried? I used prop defaultGroupingExpansionDepth based on MUI documentation:

export const EXPAND_ALL = -1;
export const COLLAPSE_ALL = 0;
...
const [expandedState, setExpandedState] = useState(COLLAPSE_ALL);
...

return <Stack>
        <Stack spacing={2} direction="row" m={1}>
            <Button variant={"contained"} onClick={() => setExpandedState(EXPAND_ALL)}>Expand All</Button>
            <Button variant={"contained"} onClick={() => setExpandedState(COLLAPSE_ALL)}>Collapse All</Button>
        </Stack>
        <DataGridPro
            treeData
            ...
            apiRef={dataGridApi}
            defaultGroupingExpansionDepth={expandedState}
            ... />
    </Stack>;

But the problem is that these buttons only work when tree is not already partially expanded.

As soon as I partially expand the tree grid, these buttons don't work any more. How can I make these buttons work irrespective of the current expansion/collapse state of the tree grid?

Shubham A.
  • 2,446
  • 4
  • 36
  • 68

1 Answers1

0

It seems like you're using the defaultGroupingExpansionDepth prop to control the initial expansion state of the DataGrid, but it might not be updating dynamically as you expand or collapse rows. To make the buttons work irrespective of the current expansion/collapse state, you can manage the expansion state using a controlled state approach:

 <DataGridPro
    treeData
    apiRef={dataGridApi}
    groupingExpansionState={expandedState === EXPAND_ALL}
    onGroupingExpandedChange={(params) =>
      setExpandedState(params.expanded ? EXPAND_ALL : COLLAPSE_ALL)
    }
    // ...
  />
Bahar
  • 81
  • 1
  • 9
  • This doesn't work. I am not getting a callback in `onGroupingExpandedChange` when I manually expand or collapse the groups/rows. ` onGroupingExpandedChange={params => { console.log(`onGroupingExpandedChange params: '${JSON.stringify(params)}'.`); setExpandedState(params.expanded ? EXPAND_ALL : COLLAPSE_ALL) }} ` – Shubham A. Aug 13 '23 at 02:46