React TreeView - Use Hierarchical Data

For an example of hierarchical data, see the following code snippet.

JavaScript
  • var hierarchicalData = [{
  • id: '1',
  • text: 'Fruits',
  • items: [
  • { id: '1_1', text: 'Apples' },
  • { id: '1_2', text: 'Oranges' }
  • ]
  • }, {
  • id: '2',
  • text: 'Vegetables',
  • items: [
  • { id: '2_1', text: 'Cucumbers' },
  • { id: '2_2', text: 'Tomatoes' }
  • ]
  • }];

View Demo

As you can see, all items in a hierarchical data source have the id and text fields, and items with children have the items field. Those are conventional field names. To use other names, change the keyExpr, displayExpr and itemsExpr properties, respectively.

App.js
  • import React from 'react';
  •  
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import TreeView from 'devextreme-react/tree-view';
  •  
  • const hierarchicalData = [{
  • key: '1',
  • name: 'Fruits',
  • children: [
  • { key: '1_1', name: 'Apples' },
  • { key: '1_2', name: 'Oranges' }
  • ]
  • }, {
  • key: '2',
  • name: 'Vegetables',
  • children: [
  • { key: '2_1', name: 'Cucumbers' },
  • { key: '2_2', name: 'Tomatoes' }
  • ]
  • }];
  •  
  • class App extends React.Component {
  • render() {
  • return (
  • <TreeView
  • keyExpr="key"
  • displayExpr="name"
  • itemsExpr="children"
  • dataSource={hierarchicalData} />
  • );
  • }
  • }
  •  
  • export default App;

Frequently, the id of an item is also its text. In this case, set both the keyExpr and displayExpr properties to a single value.

App.js
  • import React from 'react';
  •  
  • import 'devextreme/dist/css/dx.light.css';
  •  
  • import TreeView from 'devextreme-react/tree-view';
  •  
  • const hierarchicalData = [{
  • name: 'Fruits',
  • items: [
  • { name: 'Apples' },
  • { name: 'Oranges' }
  • ]
  • }, {
  • name: 'Vegetables',
  • items: [
  • { name: 'Cucumbers' },
  • { name: 'Tomatoes' }
  • ]
  • }];
  •  
  • class App extends React.Component {
  • render() {
  • return (
  • <TreeView
  • keyExpr="name"
  • displayExpr="name"
  • dataSource={hierarchicalData} />
  • );
  • }
  • }
  •  
  • export default App;
See Also