Your search did not match any results.
Tree View

Drag & Drop for Hierarchical Data Structure

This sample app demonstrates node drag and drop operations within DevExtreme TreeView when using a hierarchical data structure. You can reorder nodes within a single tree view or drag and drop nodes between two separate tree views.

Use Sortable to implement the necessary drag and drop functionality within your web app. The following steps outline configuration requirements for our JavaScript TreeView:

  1. Allow users to reorder nodes
    Wrap the TreeView in a Sortable and enable the Sortable's allowReordering option.

  2. Allow users to change node hierarchy
    Enable the allowDropInsideItem option so that users can drop one node onto another. This adds it as the target node's child. If this option is disabled, users can only drop nodes between other nodes.

  3. Allow users to drag only tree view nodes
    To specify tree view nodes as drag targets, set the filter option to a class selector. Since all tree view nodes use the dx-treeview-node class, you can use this class selector as needed.

  4. Prevent a node from being moved into its child node
    When a user moves a parent node into its own child node, it breaks the hierarchy. To prevent this outcome, implement the onDragChange function and traverse up the node tree. If the target is a child of the dragged node, cancel the ability to drop the node.

  5. Reorder nodes in code
    Implement the onDragEnd function. In this function, you must gather information about nodes being moved. With this information, you can reorder the nodes in the data source (see the moveNode function), and reassign the data source to the TreeView's items option.

  6. Specify tree view identifiers (for drag and drop between multiple tree views only)
    Identifiers help distinguish between multiple tree views. Save them in the Sortable's data option. The tree views below include the following identifiers: "driveC" and "driveD".

  7. Combine tree views into one drag and drop group (for drag and drop between multiple tree views only)
    Set the Sortable's group option to the same value for all tree views. This allows users to move nodes between the tree views.

Copy to CodeSandBox
Apply
Reset
import React from 'react'; import TreeView from 'devextreme-react/tree-view'; import Sortable from 'devextreme-react/sortable'; import service from './data.js'; class App extends React.Component { constructor(props) { super(props); this.treeViewDriveCRef = React.createRef(); this.treeViewDriveDRef = React.createRef(); this.state = { itemsDriveC: service.getItemsDriveC(), itemsDriveD: service.getItemsDriveD() }; this.onDragChange = this.onDragChange.bind(this); this.onDragEnd = this.onDragEnd.bind(this); } render() { return ( <div className="form"> <div className="drive-panel"> <div className="drive-header dx-treeview-item"><i className="dx-icon dx-icon-activefolder"></i><span>Drive C:</span></div> <Sortable filter=".dx-treeview-item" group="shared" data="driveC" allowDropInsideItem={true} allowReordering={true} onDragChange={this.onDragChange} onDragEnd={this.onDragEnd}> <TreeView id="treeviewDriveC" expandNodesRecursive={false} dataStructure="tree" ref={this.treeViewDriveCRef} items={this.state.itemsDriveC} width={250} height={380} itemRender={renderTreeViewItem} /> </Sortable> </div> <div className="drive-panel"> <div className="drive-header dx-treeview-item"><i className="dx-icon dx-icon-activefolder"></i><span>Drive D:</span></div> <Sortable filter=".dx-treeview-item" group="shared" data="driveD" allowDropInsideItem={true} allowReordering={true} onDragChange={this.onDragChange} onDragEnd={this.onDragEnd}> <TreeView id="treeviewDriveD" expandNodesRecursive={false} dataStructure="tree" ref={this.treeViewDriveDRef} items={this.state.itemsDriveD} width={250} height={380} itemRender={renderTreeViewItem} /> </Sortable> </div> </div> ); } get treeViewDriveC() { return this.treeViewDriveCRef.current.instance; } get treeViewDriveD() { return this.treeViewDriveDRef.current.instance; } onDragChange(e) { if(e.fromComponent === e.toComponent) { const fromNode = this.findNode(this.getTreeView(e.fromData), e.fromIndex); const toNode = this.findNode(this.getTreeView(e.toData), this.calculateToIndex(e)); if (toNode !== null && this.isChildNode(fromNode, toNode)) { e.cancel = true; } } } onDragEnd(e) { if(e.fromComponent === e.toComponent && e.fromIndex === e.toIndex) { return; } const fromTreeView = this.getTreeView(e.fromData); const toTreeView = this.getTreeView(e.toData); const fromNode = this.findNode(fromTreeView, e.fromIndex); const toNode = this.findNode(toTreeView, this.calculateToIndex(e)); if(e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) { return; } const fromTopVisibleNode = this.getTopVisibleNode(e.fromComponent); const toTopVisibleNode = this.getTopVisibleNode(e.toComponent); const fromItems = this.state[this.getStateFieldName(e.fromData)]; const toItems = this.state[this.getStateFieldName(e.toData)]; this.moveNode(fromNode, toNode, fromItems, toItems, e.dropInsideItem); this.setState({ [this.getStateFieldName(e.fromData)]: [...fromItems], [this.getStateFieldName(e.toData)]: [...toItems] }); fromTreeView.scrollToItem(fromTopVisibleNode); toTreeView.scrollToItem(toTopVisibleNode); } getTreeView(driveName) { return driveName === 'driveC' ? this.treeViewDriveC : this.treeViewDriveD; } getStateFieldName(driveName) { return driveName === 'driveC' ? 'itemsDriveC' : 'itemsDriveD'; } calculateToIndex(e) { if(e.fromComponent != e.toComponent || e.dropInsideItem) { return e.toIndex; } return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1; } findNode(treeView, index) { const visibleItems = []; this.buildVisibleNodesArray(treeView.getNodes(), visibleItems); if(visibleItems.length <= index) { return null; } return visibleItems[index]; } buildVisibleNodesArray(nodes, arrayContainer) { for(var i = 0; i < nodes.length; i++) { arrayContainer.push(nodes[i]); if(nodes[i].expanded !== false && nodes[i].children) { this.buildVisibleNodesArray(nodes[i].children, arrayContainer); } } } moveNode(fromNode, toNode, fromItems, toItems, isDropInsideItem) { const fromNodeContainingArray = this.getNodeContainingArray(fromNode, fromItems); const fromIndex = fromNodeContainingArray.findIndex(item => item.id == fromNode.itemData.id); fromNodeContainingArray.splice(fromIndex, 1); if(isDropInsideItem) { toNode.itemData.items.splice(toNode.itemData.items.length, 0, fromNode.itemData); } else { const toNodeContainingArray = this.getNodeContainingArray(toNode, toItems); const toIndex = toNode === null ? toNodeContainingArray.length : toNodeContainingArray.findIndex(item => item.id == toNode.itemData.id); toNodeContainingArray.splice(toIndex, 0, fromNode.itemData); } } getNodeContainingArray(node, rootArray) { return node === null || node.parent === null ? rootArray : node.parent.itemData.items; } isChildNode(parentNode, childNode) { let parent = childNode.parent; while(parent !== null) { if(parent.itemData.id === parentNode.itemData.id) { return true; } parent = parent.parent; } return false; } getTopVisibleNode(component) { const treeViewElement = component.element(); const treeViewTopPosition = treeViewElement.getBoundingClientRect().top; const nodes = treeViewElement.querySelectorAll('.dx-treeview-node'); for(let i = 0; i < nodes.length; i++) { const nodeTopPosition = nodes[i].getBoundingClientRect().top; if(nodeTopPosition >= treeViewTopPosition) { return nodes[i]; } } return null; } } function renderTreeViewItem(item) { return <div><i className={item.isDirectory ? 'dx-icon dx-icon-activefolder' : 'dx-icon dx-icon-file'}></i><span>{ item.name }</span></div>; } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render( <App />, document.getElementById('app') );
<!DOCTYPE html> <html> <head> <title>DevExtreme Demo</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.1.8/css/dx.common.css" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.1.8/css/dx.light.css" /> <link rel="stylesheet" type="text/css" href="styles.css" /> <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script> <script src="https://unpkg.com/systemjs@0.21.3/dist/system.js"></script> <script type="text/javascript" src="config.js"></script> <script type="text/javascript"> System.import('./index.js'); </script> </head> <body class="dx-viewport"> <div class="demo-container"> <div id="app"></div> </div> </body> </html>
.form { display: flex; } .form>div { display: inline-block; vertical-align: top; } #treeviewDriveC, #treeviewDriveD { margin-top: 10px; } .drive-header { min-height: auto; padding: 0px; cursor: default; } .drive-header .dx-icon { margin-top: -4px; } .drive-panel { padding: 20px 30px; font-size: 115%; font-weight: bold; border-right: 1px solid rgba(165, 165, 165, 0.4); height: 100%; } .drive-panel:last-of-type { border-right: none; }
const itemsDriveD = []; const itemsDriveC = [{ id: '1', name: 'Documents', isDirectory: true, expanded: true, items: [ { id: '2', name: 'Projects', isDirectory: true, expanded: true, items: [ { id: '3', name: 'About.rtf', isDirectory: false }, { id: '4', name: 'Passwords.rtf', isDirectory: false } ] }, { id: '5', name: 'About.xml', isDirectory: false }, { id: '6', name: 'Managers.rtf', isDirectory: false }, { id: '7', name: 'ToDo.txt', isDirectory: false } ], }, { id: '8', name: 'Images', isDirectory: true, expanded: true, items: [ { id: '9', name: 'logo.png', isDirectory: false }, { id: '10', name: 'banner.gif', isDirectory: false } ] }, { id: '11', name: 'System', isDirectory: true, expanded: true, items: [ { id: '12', name: 'Employees.txt', isDirectory: false }, { id: '13', name: 'PasswordList.txt', isDirectory: false } ] }, { id: '14', name: 'Description.rtf', isDirectory: false }, { id: '15', name: 'Description.txt', isDirectory: false }]; export default { getItemsDriveC() { return itemsDriveC; }, getItemsDriveD() { return itemsDriveD; } };
System.config({ transpiler: 'plugin-babel', meta: { }, paths: { 'npm:': 'https://unpkg.com/' }, defaultExtension: 'js', map: { 'react': 'npm:react@16/umd/react.development.js', 'react-dom': 'npm:react-dom@16/umd/react-dom.development.js', 'prop-types': 'npm:prop-types/prop-types.js', 'devextreme': 'npm:devextreme@20.1', 'devextreme-react': 'npm:devextreme-react@20.1', 'jszip': 'npm:jszip@3.1.3/dist/jszip.min.js', 'quill': 'npm:quill@1.3.7/dist/quill.js', 'devexpress-diagram': 'npm:devexpress-diagram@1.0.17', 'devexpress-gantt': 'npm:devexpress-gantt@1.0.10', // SystemJS plugins 'plugin-babel': 'npm:systemjs-plugin-babel@0/plugin-babel.js', 'systemjs-babel-build': 'npm:systemjs-plugin-babel@0/systemjs-babel-browser.js' }, packages: { 'devextreme': { defaultExtension: 'js' }, 'devextreme-react': { main: 'index.js' }, 'devextreme/events/utils': { main: 'index' }, 'devextreme/events': { main: 'index' }, }, babelOptions: { sourceMaps: false, stage0: true, react: true } });