Expanding All Items

While the TreeView does not provide a built-in feature for expanding and collapsing all its items at once, the component supports such an implementation.

To enable the expand-all mode for its items, set the expanded field of each TreeView node to true. To enable the collapse-all mode for its items, set the expanded field of each TreeView node to a falsy value. You can further handle the expanding and collapsing of all items depending on the approach you selected for updating the expanded TreeView items.

The following example demonstrates how to copy the data before each update of the expanded field.

class App extends React.Component {
    state = { data: tree };

    render() {
        return (
            <div>
                <div className='example-config'>
                    <button onClick={this.expandAll} className='k-button'>Expand all</button>
                    <button onClick={this.collapseAll} className='k-button'>Collapse all</button>
                </div>
                <TreeView data={this.state.data} expandIcons={true} onExpandChange={this.onExpandChange} />
            </div>
        );
    }
    expandAll = () => {
        this.setState({
            data: this.state.data.map(item => Object.assign({}, item, { expanded: true }))
        });
    }
    collapseAll = () => {
        this.setState({
            data: this.state.data.map(item => Object.assign({}, item, { expanded: false }))
        });
    }
    onExpandChange = (event) => {
        const data = this.state.data.slice();

        const itemIndex = data.indexOf(event.item);
        data[itemIndex] = { ...event.item };
        data[itemIndex].expanded = !data[itemIndex].expanded;

        this.setState({ data });
    }
}

const tree = [
    { text: 'Item1', items: [{ text: 'Item1.1' }, { text: 'Item1.2' }] },
    { text: 'Item2', items: [{ text: 'Item2.1' }, { text: 'Item2.2' }] },
    { text: 'Item3', items: [{ text: 'Item3.1' }, { text: 'Item3.2' }] },
    { text: 'Item4', items: [{ text: 'Item4.1' }, { text: 'Item4.2' }] },
    { text: 'Item5', items: [{ text: 'Item5.1' }, { text: 'Item5.2' }] },
    { text: 'Item6', items: [{ text: 'Item6.1' }, { text: 'Item6.2' }] }
];

ReactDOM.render(
    <App />,
    document.querySelector('my-app')
);
In this article
 /