How to Create React Sortable Tree

A React component for Drag-and-drop sortable representation of hierarchical data.

We are going to see how we can use react sortable tree . lets get started .

InstallĀ react-sortable-tree :

npm install react-sortable-tree --save

yarn add react-sortable-tree

Props of react-sortable-tree

PropsTypeDescription
treeData
(required)
object[]Tree data with the following keys:title is the primary label for the node.subtitle is a secondary label for the node.expanded shows children of the node if true, or hides them if false. Defaults to false.children is an array of child nodes belonging to the node.Example[{title: 'main', subtitle: 'sub'}, { title: 'value2', expanded: true, children: [{ title: 'value3') }] }]
onChange
(required)
funcCalled whenever tree data changed. Just like with React input elements, you have to update your own component’s data to see the changes reflected.( treeData: object[] ): void
getNodeKey
(recommended)
funcSpecify the unique key used to identify each node and generate the path array passed in callbacks. With a setting of getNodeKey={({ node }) => node.id}, for example, in callbacks this will let you easily determine that the node with an id of 35 is (or has just become) a child of the node with an id of 12, which is a child of … and so on. It uses defaultGetNodeKey by default, which returns the index in the tree (omitting hidden nodes).({ node: object, treeIndex: number }): string or number
generateNodePropsfuncGenerate an object with additional props to be passed to the node renderer. Use this for adding buttons via the buttons key, or additional style / className settings.({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): object
onMoveNodefuncCalled after node move operation.({ treeData: object[], node: object, nextParentNode: object, prevPath: number[] or string[], prevTreeIndex: number, nextPath: number[] or string[], nextTreeIndex: number }): void
onVisibilityTogglefuncCalled after children nodes collapsed or expanded.({ treeData: object[], node: object, expanded: bool, path: number[] or string[] }): void
onDragStateChangedfuncCalled when a drag is initiated or ended.({ isDragging: bool, draggedNode: object }): void
maxDepthnumberMaximum depth nodes can be inserted at. Defaults to infinite.
rowDirectionstringAdds row direction support if set to 'rtl' Defaults to 'ltr'.
canDragfunc or boolReturn false from callback to prevent node from dragging, by hiding the drag handle. Set prop to false to disable dragging on all nodes. Defaults to true.({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): bool
canDropfuncReturn false to prevent node from dropping in the given location.({ node: object, prevPath: number[] or string[], prevParent: object, prevTreeIndex: number, nextPath: number[] or string[], nextParent: object, nextTreeIndex: number }): bool
canNodeHaveChildrenfuncFunction to determine whether a node can have children, useful for preventing hover preview when you have a canDrop condition. Default is set to a function that returns true. Functions should be of type (node): bool.
themeobjectSet an all-in-one packaged appearance for the tree. See the Themes section for more information.
searchMethodfuncThe method used to search nodes. Defaults to defaultSearchMethod, which uses the searchQuery string to search for nodes with matching title or subtitle values. NOTE: Changing searchMethod will not update the search, but changing the searchQuery will.({ node: object, path: number[] or string[], treeIndex: number, searchQuery: any }): bool
searchQuerystring or anyUsed by the searchMethod to highlight and scroll to matched nodes. Should be a string for the default searchMethod, but can be anything when using a custom search. Defaults to null.
searchFocusOffsetnumberOutline the <searchFocusOffset>th node and scroll to it.
onlyExpandSearchedNodesbooleanOnly expand the nodes that match searches. Collapses all other nodes. Defaults to false.
searchFinishCallbackfuncGet the nodes that match the search criteria. Used for counting total matches, etc.(matches: { node: object, path: number[] or string[], treeIndex: number }[]): void
dndTypestringString value used by react-dnd (see overview at the link) for dropTargets and dragSources types. If not set explicitly, a default value is applied by react-sortable-tree for you for its internal use. NOTE: Must be explicitly set and the same value used in order for correct functioning of external nodes
shouldCopyOnOutsideDropfunc or boolReturn true, or a callback returning true, and dropping nodes to react-dnd drop targets outside of the tree will not remove them from the tree. Defaults to false.({ node: object, prevPath: number[] or string[], prevTreeIndex: number, }): bool
reactVirtualizedListPropsobjectCustom properties to hand to the internal react-virtualized List
styleobjectStyle applied to the container wrapping the tree (style defaults to {height: '100%'})
innerStyleobjectStyle applied to the inner, scrollable container (for padding, etc.)
classNamestringClass name for the container wrapping the tree
rowHeightnumber or funcUsed by react-sortable-tree. Defaults to 62. Either a fixed row height (number) or a function that returns the height of a row given its index: ({ treeIndex: number, node: object, path: number[] or string[] }): number
slideRegionSizenumberSize in px of the region near the edges that initiates scrolling on dragover. Defaults to 100.
scaffoldBlockPxWidthnumberThe width of the blocks containing the lines representing the structure of the tree. Defaults to 44.
isVirtualizedboolSet to false to disable virtualization. Defaults to trueNOTE: Auto-scrolling while dragging, and scrolling to the searchFocusOffset will be disabled.
nodeContentRendereranyOverride the default component (NodeRendererDefault) for rendering nodes (but keep the scaffolding generator). This is a last resort for customization – most custom styling should be able to be solved with generateNodeProps, a theme or CSS rules. If you must use it, is best to copy the component in node-renderer-default.js to use as a base, and customize as needed.
placeholderRendereranyOverride the default placeholder component (PlaceholderRendererDefault) which is displayed when the tree is empty. This is an advanced option, and in most cases should probably be solved with a theme or custom CSS instead.

Examples :

  1. Simple sortable tree
import React, { Component } from 'react';
import SortableTree from 'react-sortable-tree';
import 'react-sortable-tree/style.css'; // This only needs to be imported once in your app
 
export default class SortTree extends Component {
  constructor(props) {
    super(props);
 
    this.state = {
      treeData: [
        { title: 'Comic Books', children: [{ title: 'Amazing Spider-Man' },{ title: 'The Incredible Hulk' },{ title: 'Action Comics' },{ title: 'Batman' },{ title: 'New Avengers' }] },
        { title: 'Historical Fiction', children: [{ title: 'The Help' },{ title: 'All the Light We Cannot See' },{ title: ' The Color Purple' },{ title: ' War and Peace' }] },
      ],
    };
  }
 
  render() {
    return (
      <div style={{ height: 800 }}>
        <SortableTree
          treeData={this.state.treeData}
          onChange={treeData => this.setState({ treeData })}
        />
      </div>
    );
  }
}

2. Sortable tree with Expend and Collapse functionality

import React, { Component } from 'react';
import SortableTree,  {toggleExpandedForAll} from 'react-sortable-tree';
import { Button, Divider} from 'semantic-ui-react';
import 'react-sortable-tree/style.css'; // This only needs to be imported once in your app
 
export default class SortTree extends Component {
  constructor(props) {
    super(props);
 
    this.state = {
      treeData: [
        { title: 'Comic Books', children: [{ title: 'Amazing Spider-Man' },{ title: 'The Incredible Hulk' },{ title: 'Action Comics' },{ title: 'Batman' },{ title: 'New Avengers' }] },
        { title: 'Historical Fiction', children: [{ title: 'The Help' },{ title: 'All the Light We Cannot See' },{ title: ' The Color Purple' },{ title: ' War and Peace' }] },
      ],
    };
  }

  expandAndCollapse = (expanded) => {
    this.setState({
      treeData: toggleExpandedForAll({
        treeData: this.state.treeData,
        expanded,
      }),
    });
   };
 
  render() {
    return (
      <div style={{ height: 800 }}>
        <h2>React Sortable Tree</h2>
        <Divider></Divider>
        <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(true); }}>Expand all</Button>
        <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(false); }}>Collapse all</Button>
        <SortableTree
          treeData={this.state.treeData}
          onChange={treeData => this.setState({ treeData })}
        />
      </div>
    );
  }
}

3. Sortable tree with search functionality

import React, { Component } from 'react';
import SortableTree, { toggleExpandedForAll } from 'react-sortable-tree';
import { Button, Divider, Input } from 'semantic-ui-react';
import 'react-sortable-tree/style.css';

export default class SortTree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      searchString: '',
      searchFocusIndex: 0,
      treeData: [
        { title: 'Comic Books', children: [{ title: 'Amazing Spider-Man' }, { title: 'The Incredible Hulk' }, { title: 'Action Comics' }, { title: 'Batman' }, { title: 'New Avengers' }] },
        { title: 'Historical Fiction Books', children: [{ title: 'The Help' }, { title: 'All the Light We Cannot See' }, { title: ' The Color Purple' }, { title: ' War and Peace' }] },
      ],
    };
  }

  expandAndCollapse = (expanded) => {
    this.setState({
      treeData: toggleExpandedForAll({
        treeData: this.state.treeData,
        expanded,
      }),
    });
  };

  updateTreeData(treeData) {
    this.setState({ treeData });
  }

  render() {
    const { searchString, searchFocusIndex, treeData } = this.state;
    return (
      <div style={{ height: 800 }}>
        <div style={{ flex: '0 0 auto', padding: '0 15px' }}>
          <h2>React Sortable Tree</h2>
          <Divider></Divider>
          <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(true); }}>Expand all</Button>
          <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(false); }}>Collapse all</Button>&nbsp;&nbsp;&nbsp;
          <Input size='mini' placeholder='Search' value={searchString}
            onChange={event => this.setState({ searchString: event.target.value })}/>
        </div> 
        <Divider></Divider>
        <SortableTree
          searchQuery={searchString}
          onChange={this.updateTreeData}
          searchFocusOffset={searchFocusIndex}
          treeData={treeData}
          onChange={treeData => this.setState({ treeData })}
        />
      </div>
    );
  }
}

4. Sortable tree with insert and delete nodes

import React, { Component } from 'react';
import SortableTree, { toggleExpandedForAll, changeNodeAtPath, insertNode, removeNodeAtPath } from 'react-sortable-tree';
import { Button, Divider, Input, Popup, Icon } from 'semantic-ui-react';
import 'react-sortable-tree/style.css';

export default class SortTree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      searchString: '',
      searchFocusIndex: 0,
      currentNode: {},
      treeData: [
        { title: 'Comic Books', children: [{ title: 'Amazing Spider-Man' }, { title: 'The Incredible Hulk' }, { title: 'Action Comics' }, { title: 'Batman' }, { title: 'New Avengers' }] },
        { title: 'Historical Fiction Books', children: [{ title: 'The Help' }, { title: 'All the Light We Cannot See' }, { title: ' The Color Purple' }, { title: ' War and Peace' }] },
      ],
    };
  }

  expandAndCollapse = (expanded) => {
    this.setState({
      treeData: toggleExpandedForAll({
        treeData: this.state.treeData,
        expanded,
      }),
    });
  };

  updateTreeData(treeData) {
    this.setState({ treeData });
  }
  removeNode = (path) => {
    this.setState(state => ({
      treeData: removeNodeAtPath({
        treeData: state.treeData,
        path,
        getNodeKey: ({ treeIndex }) => treeIndex,
      })
    }));
  }
  selectThis = (node, path) => {
    this.setState({ currentNode: node, path: path });
  }
  insertNewNode = () => {
    this.setState(state => ({
      treeData: insertNode({
        treeData: state.treeData,
        depth: 0,
        minimumTreeIndex: state.treeData.length,
        newNode: { title: "", children: [] },
        getNodeKey: ({ treeIndex }) => treeIndex
      }).treeData
    }));
  }

  render() {
    const { searchString, searchFocusIndex, treeData } = this.state;
    const getNodeKey = ({ treeIndex }) => treeIndex;

    return (
      <div style={{ height: 800 }}>
        <div style={{ flex: '0 0 auto', padding: '0 15px' }}>
          <h2>React Sortable Tree</h2>
          <Divider></Divider>
          <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(true); }}>Expand all</Button>
          <Button size='mini' color='blue' onClick={() => { this.expandAndCollapse(false); }}>Collapse all</Button>&nbsp;&nbsp;&nbsp;
          <Input size='mini' placeholder='Search' value={searchString}
            onChange={event => this.setState({ searchString: event.target.value })} />
        </div>
        <Divider></Divider>
        <SortableTree
          searchQuery={searchString}
          onChange={this.updateTreeData}
          searchFocusOffset={searchFocusIndex}
          treeData={treeData}
          onChange={treeData => this.setState({ treeData })}
          generateNodeProps={({ node, path }) => ({
            title: (
              <form onClick={(e) => { e.preventDefault(); e.stopPropagation(); this.selectThis(node, path); }}>
                <input
                  style={{ fontSize: "1rem", width: 200 }}
                  value={node.title}
                  onChange={event => {
                    const title = event.target.value;
                    this.setState(state => ({
                      treeData: changeNodeAtPath({
                        treeData: state.treeData,
                        path,
                        getNodeKey,
                        newNode: { ...node, title }
                      })
                    }));
                  }}
                />&nbsp;&nbsp;&nbsp;
                <Button size='mini' basic color='blue' circular icon='add' onClick={(e) => { e.preventDefault(); e.stopPropagation(); this.insertNewNode(path) }} />
                <Button size='mini' basic color='blue' circular icon='trash' onClick={(e) => { e.preventDefault(); e.stopPropagation(); this.removeNode(path) }} />
              </form>
            )
          })}
        />
      </div>
    );
  }
}

Conclusion :-