Expand and collapse all nodes in MUI DataGrid through ReactJS programming
P粉068486220
P粉068486220 2023-08-13 10:39:36
0
1
673
<p>How to make all rows expand/collapse programmatically in <code>DataGrid</code> in MUI ReactJS? </p> <p><strong>What have I tried? </strong> I used the <code>defaultGroupingExpansionDepth</code> property according to the MUI documentation: </p> <pre class="brush:php;toolbar:false;">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>;</pre> <p>The problem is, these buttons only work when the tree is <strong>not</strong> partially expanded. </p> <p>Once I partially expand the tree grid, the buttons no longer work. How can I make these buttons work regardless of the current expanded/collapsed state of the tree grid? </p>
P粉068486220
P粉068486220

reply all(1)
P粉722521204

It looks like you are using the defaultGroupingExpansionDepth property to control the initial expansion state of the DataGrid, but it may not update dynamically as you expand or collapse rows. In order to make the button work in the current expanded/collapsed state, you can use the controlled state method to manage the expanded state:

<DataGridPro
    treeData
    apiRef={dataGridApi}
    groupingExpansionState={expandedState === EXPAND_ALL}
    onGroupingExpandedChange={(params) =>
      setExpandedState(params.expanded ? EXPAND_ALL : COLLAPSE_ALL)
    }
    // ...
  />
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template