---
product: "AG Grid"
title: "Tree Data - Expanding Groups"
description: "Configure the initial expanded group row state when using Tree Data."
enterprise: true
framework: react
version: "36.2.0"
related:
    - title: "Overview"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data/"
    - title: "Supplying Data"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data-data/"
    - title: "Group Column"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data-group-column/"
    - title: "Tree Selection"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data-selection/"
    - title: "Filtering"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data-filtering/"
    - title: "Tree Row Dragging"
      url: "https://www.ag-grid.com/archive/36.2.0/react-data-grid/tree-data-row-dragging/"
llms: "https://www.ag-grid.com/archive/36.2.0/llms.txt"
---

# Tree Data - Expanding Groups

Configure the initial expanded group row state when using Tree Data.

## Expanding by Group Level

When providing a hierarchy, all levels will default to a collapsed state. This can be configured by setting the `groupDefaultExpanded` grid option. Providing a number will expand all groups down to that level, or providing -1 will expand all groups.

#### Group Default Expanded

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  AutoGroupColumnDef,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GetDataPath,
  GridApi,
  GridOptions,
  ModuleRegistry,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { TreeDataModule } from "ag-grid-enterprise";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

const modules = [ClientSideRowModelModule, TreeDataModule, TextFilterModule];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "created" },
    { field: "modified" },
    {
      field: "size",
      aggFunc: "sum",
      valueFormatter: (params) => {
        if (params.value == null) {
          return ""; // params.value can be null/undefined here (e.g. no size for this row)
        }
        const sizeInKb = params.value / 1024;
        if (sizeInKb > 1024) {
          return `${+(sizeInKb / 1024).toFixed(2)} MB`;
        } else {
          return `${+sizeInKb.toFixed(2)} KB`;
        }
      },
    },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
    };
  }, []);
  const autoGroupColumnDef = useMemo<AutoGroupColumnDef>(() => {
    return {
      headerName: "File Explorer",
      minWidth: 280,
      filter: "agTextColumnFilter",
      cellRendererParams: {
        suppressCount: true,
      },
    };
  }, []);
  const getDataPath = useCallback((data) => data.path, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            autoGroupColumnDef={autoGroupColumnDef}
            groupDefaultExpanded={1}
            treeData={true}
            getDataPath={getDataPath}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Group Default Expanded](https://www.ag-grid.com/archive/36.2.0/examples/tree-data-opening-groups/group-default-expanded/reactFunctionalTs/)

The example above uses the following configuration to expand the first level of groups, but no others:

```jsx
const groupDefaultExpanded = 1;

<AgGridReact groupDefaultExpanded={groupDefaultExpanded} />
```

## Expanding via Callback

To granularly determine which groups should be expanded by default, use the `isGroupOpenByDefault` grid callback.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `isGroupOpenByDefault` | `IsGroupOpenByDefault` |  |  |  |

#### Open by Default

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  AutoGroupColumnDef,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DateFilterModule,
  GetDataPath,
  GridApi,
  GridOptions,
  IsGroupOpenByDefault,
  IsGroupOpenByDefaultParams,
  ModuleRegistry,
  NumberFilterModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { TreeDataModule } from "ag-grid-enterprise";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

const modules = [
  ClientSideRowModelModule,
  TreeDataModule,
  TextFilterModule,
  NumberFilterModule,
  DateFilterModule,
];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "created", filter: "agDateColumnFilter" },
    { field: "modified", filter: "agDateColumnFilter" },
    {
      field: "size",
      filter: "agNumberColumnFilter",
      aggFunc: "sum",
      valueFormatter: (params) => {
        if (params.value == null) {
          return ""; // params.value can be null/undefined here (e.g. no size for this row)
        }
        const sizeInKb = params.value / 1024;
        if (sizeInKb > 1024) {
          return `${+(sizeInKb / 1024).toFixed(2)} MB`;
        } else {
          return `${+sizeInKb.toFixed(2)} KB`;
        }
      },
    },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
    };
  }, []);
  const autoGroupColumnDef = useMemo<AutoGroupColumnDef>(() => {
    return {
      headerName: "File Explorer",
      minWidth: 280,
      filter: "agTextColumnFilter",
      cellRendererParams: {
        suppressCount: true,
      },
    };
  }, []);
  const isGroupOpenByDefault = useCallback(
    (params: IsGroupOpenByDefaultParams) => {
      return (
        (params.level === 0 && params.key === "Documents") ||
        (params.level === 1 && params.key === "Work") ||
        (params.level === 2 && params.key === "ProjectBeta")
      );
    },
    [],
  );
  const getDataPath = useCallback((data) => data.path, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            autoGroupColumnDef={autoGroupColumnDef}
            isGroupOpenByDefault={isGroupOpenByDefault}
            treeData={true}
            getDataPath={getDataPath}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Open by Default](https://www.ag-grid.com/archive/36.2.0/examples/tree-data-opening-groups/open-by-default/reactFunctionalTs/)

The example above uses the following configuration to expand the `ProjectBeta` groups by default:

```jsx
const isGroupOpenByDefault = (params) => {
    return (
        (params.level === 0 && params.key === 'Documents') ||
        (params.level === 1 && params.key === 'Work') ||
        (params.level === 2 && params.key === 'ProjectBeta')
    );
};

<AgGridReact isGroupOpenByDefault={isGroupOpenByDefault} />
```

> **Note**
>
> Row keys are not always unique, so it is recommended to instead use the node ID or data path to identify the row.

## Scrolling Child Rows into View

When expanding a group the vertical scroll does not change, which can result in the child rows not being visible. You can use the `ensureIndexVisible()` function on the API to ensure the index is visible, scrolling the table if needed.

In the example below, if you expand a group at the bottom, the grid will scroll so that all of the children of the group are visible.

#### Row Group Scroll

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  AutoGroupColumnDef,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DateFilterModule,
  GetDataPath,
  GridApi,
  GridOptions,
  ModuleRegistry,
  NumberFilterModule,
  RowGroupOpenedEvent,
  ScrollApiModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { TreeDataModule } from "ag-grid-enterprise";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

const modules = [
  ScrollApiModule,
  ClientSideRowModelModule,
  TreeDataModule,
  TextFilterModule,
  NumberFilterModule,
  DateFilterModule,
];

const GridExample = () => {
  const gridRef = useRef<AgGridReact>(null);
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "created", filter: "agDateColumnFilter" },
    { field: "modified", filter: "agDateColumnFilter" },
    {
      field: "size",
      filter: "agNumberColumnFilter",
      aggFunc: "sum",
      valueFormatter: (params) => {
        if (params.value == null) {
          return ""; // params.value can be null/undefined here (e.g. no size for this row)
        }
        const sizeInKb = params.value / 1024;
        if (sizeInKb > 1024) {
          return `${+(sizeInKb / 1024).toFixed(2)} MB`;
        } else {
          return `${+sizeInKb.toFixed(2)} KB`;
        }
      },
    },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
    };
  }, []);
  const autoGroupColumnDef = useMemo<AutoGroupColumnDef>(() => {
    return {
      headerName: "File Explorer",
      minWidth: 280,
      filter: "agTextColumnFilter",
      cellRendererParams: {
        suppressCount: true,
      },
    };
  }, []);
  const getDataPath = useCallback((data) => data.path, []);

  const onRowGroupOpened = useCallback(
    (event: RowGroupOpenedEvent<IOlympicData>) => {
      if (event.expanded) {
        const rowNodeIndex = event.node.rowIndex!;
        // factor in child nodes so we can scroll to correct position
        const childCount = event.node.childrenAfterSort
          ? event.node.childrenAfterSort.length
          : 0;
        const newIndex = rowNodeIndex + childCount;
        gridRef.current!.api.ensureIndexVisible(newIndex);
      }
    },
    [],
  );

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            ref={gridRef}
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            autoGroupColumnDef={autoGroupColumnDef}
            treeData={true}
            getDataPath={getDataPath}
            animateRows={false}
            onRowGroupOpened={onRowGroupOpened}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Row Group Scroll](https://www.ag-grid.com/archive/36.2.0/examples/tree-data-opening-groups/row-group-scroll/reactFunctionalTs/)

## API

The grid exposes API methods to expand or collapse groups programmatically.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `expandAll` | `Function` |  |  |  |
| `collapseAll` | `Function` |  |  |  |
| `setRowNodeExpanded` | `Function` |  |  |  |

### Expand Row Ancestors

When expanding rows via the API, the `setRowNodeExpanded` function can be used to expand a specific row as well as all of its ancestors.

#### Expand to Row

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import {
  AutoGroupColumnDef,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DateFilterModule,
  GetDataPath,
  GetRowIdFunc,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  NumberFilterModule,
  RowApiModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { TreeDataModule } from "ag-grid-enterprise";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

const modules = [
  RowApiModule,
  ClientSideRowModelModule,
  TreeDataModule,
  TextFilterModule,
  NumberFilterModule,
  DateFilterModule,
];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { field: "created", filter: "agDateColumnFilter" },
    { field: "modified", filter: "agDateColumnFilter" },
    {
      field: "size",
      filter: "agNumberColumnFilter",
      aggFunc: "sum",
      valueFormatter: (params) => {
        if (params.value == null) {
          return ""; // params.value can be null/undefined here (e.g. no size for this row)
        }
        const sizeInKb = params.value / 1024;
        if (sizeInKb > 1024) {
          return `${+(sizeInKb / 1024).toFixed(2)} MB`;
        } else {
          return `${+sizeInKb.toFixed(2)} KB`;
        }
      },
    },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
    };
  }, []);
  const autoGroupColumnDef = useMemo<AutoGroupColumnDef>(() => {
    return {
      headerName: "File Explorer",
      minWidth: 280,
      filter: "agTextColumnFilter",
      cellRendererParams: {
        suppressCount: true,
      },
    };
  }, []);
  const getDataPath = useCallback((data) => data.path, []);
  const getRowId = useCallback(
    (params) => params.data.path[params.data.path.length - 1],
    [],
  );

  const onGridReady = useCallback((params: GridReadyEvent) => {
    const node = params.api.getRowNode("Proposal.docx");
    if (node) {
      params.api.setRowNodeExpanded(node, true, true);
    }
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div style={gridStyle}>
          <AgGridReact
            rowData={rowData}
            columnDefs={columnDefs}
            defaultColDef={defaultColDef}
            autoGroupColumnDef={autoGroupColumnDef}
            treeData={true}
            getDataPath={getDataPath}
            getRowId={getRowId}
            onGridReady={onGridReady}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Expand to Row](https://www.ag-grid.com/archive/36.2.0/examples/tree-data-opening-groups/expand-collapse-api/reactFunctionalTs/)

The example above uses [Row IDs](https://www.ag-grid.com/archive/36.2.0/react-data-grid/row-ids/#row-ids) to demonstrate the following configuration to expand all of the 'Proposal.docx' row's ancestors:

```
const expandToRow = () => {
  const node = gridApi.getRowNode('Proposal.docx');
  if (node) {
      gridApi.setRowNodeExpanded(node, true, true);
  }
}
```
