Search code examples
reactjsag-gridag-grid-react

can we toggle between tree view and flat view?


Is it possible to provide a feature that allows user to have both tree view and flat view options for same data in the same grid

For eg

Tree view

I can see data as nested/linked

Parent row

  • child row

In flat view: just display child rows

child row


Solution

  • If you want to flatten the tree, simply return the last item in the tree path. You also need to reset all rows to apply the change.

    const displayTree = React.useRef(true);
    const updateDisplayTree = (tree) => () => {
      displayTree.current = tree;
      gridApi.setRowData(rowData);
    };
    
    ...
    
    <button onClick={updateDisplayTree(true)}>Tree</button>
    <button onClick={updateDisplayTree(false)}>Flat</button>
    <AgGridReact
      treeData
      autoGroupColumnDef={{
        headerName: "Organisation Hierarchy",
        minWidth: 300,
      }}
      getDataPath={(data) => {
        if (displayTree.current) {
          return data.orgHierarchy;
        } else {
          return data.orgHierarchy.slice(-1);
        }
      }}
      {...}
    />
    

    Live Demo

    Edit AgGrid Tree Last Child (forked)