React TreeList - Expand and Collapse Rows
TreeList allows you to configure expanded rows on initialization, and expand/collapse rows programmatically.
API
All TreeList rows are initially collapsed. If you enable autoExpandAll, all rows are initially expanded. Specify the expandedRowKeys array to expand specific rows. To expand a nested row, include all parent row keys (in addition to the nested row key) in expandedRowKeys.
- import { TreeList } from 'devextreme-react/tree-list';
- function App() {
- return (
- {/* Expand specific rows */}
- <TreeList ...
- defaultExpandedRowKeys={[1, 5, 18]}
- />
- {/* Expand all rows */}
- <TreeList ...
- autoExpandAll={true}
- />
- );
- }
To expand/collapse rows at runtime, call expandRow(key)/collapseRow(key) or modify the expandedRowKeys array. To collapse all rows, set expandedRowKeys to an empty array ([]).
To toggle a row between expanded and collapsed states, you can implement the isRowExpanded(key) method as follows:
- import React, { useRef } from 'react';
- import { TreeList } from 'devextreme-react/tree-list';
- function App() {
- const treeList = useRef(null);
- function toggleRow(key) {
- if (treeList.current.instance().isRowExpanded(key)) {
- treeList.current.instance().collapseRow(key);
- } else {
- treeList.current.instance().expandRow(key);
- }
- };
- return (
- <TreeList ...
- ref="treeList"
- />
- );
- }
See Also
Events
To execute certain commands before or after a row was expanded or collapsed, handle the rowExpanding, rowExpanded, rowCollapsing or rowCollapsed event. Assign event handling functions to the corresponding onEventName properties when you configure the UI component if these functions are going to remain unchanged.
- import React from 'react';
- import 'devextreme/dist/css/dx.fluent.blue.light.css';
- import TreeList from 'devextreme-react/tree-list';
- const onRowExpanding = (e) => {
- // Handler of the "rowExpanding" event
- };
- const onRowExpanded = (e) => {
- // Handler of the "rowExpanded" event
- };
- const onRowCollapsing = (e) => {
- // Handler of the "rowCollapsing" event
- };
- const onRowCollapsed = (e) => {
- // Handler of the "rowCollapsed" event
- };
- export default function App() {
- return (
- <TreeList ...
- onRowExpanding={onRowExpanding}
- onRowExpanded={onRowExpanded}
- onRowCollapsing={onRowCollapsing}
- onRowCollapsed={onRowCollapsed}>
- </TreeList>
- );
- }