/react-sortable-tree

Drag-and-drop sortable component for nested data and hierarchies

Primary LanguageJavaScriptMIT LicenseMIT

React Sortable Tree

NPM

tree200

demo

Features

  • Works right out of the box, but is highly customizable

Example

import React, { Component } from 'react';
import SortableTree from 'react-sortable-tree';

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

        this.state = {
            treeData: [{ title: 'Chicken', children: [ { title: 'Egg' } ] }],
        };
    }

    render() {
        return (
            <div style={{ height: 400 }}>
                <SortableTree
                    treeData={this.state.treeData}
                    onChange={treeData => this.setState({ treeData })}
                />
            </div>
        );
    }
}

Options

Property Type Default Required Description
treeData object[] yes 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 func yes Called 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
style object {} Style applied to the container wrapping the tree (style defaults to {height: '100%'})
className string Class name for the container wrapping the tree
dndType string String 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
innerStyle object {} Style applied to the inner, scrollable container (for padding, etc.)
maxDepth number Maximum depth nodes can be inserted at. Defaults to infinite.
searchMethod func The method used to search nodes. Defaults to a function that 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
searchQuery string or any null Used 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.
searchFocusOffset number Outline the <searchFocusOffset>th node and scroll to it.
searchFinishCallback func Get the nodes that match the search criteria. Used for counting total matches, etc.
(matches: { node: object, path: number[] or string[], treeIndex: number }[]): void
generateNodeProps func Generate 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
getNodeKey func defaultGetNodeKey Determine the unique key used to identify each node and generate the path array passed in callbacks. By default, returns the index in the tree (omitting hidden nodes).
({ node: object, treeIndex: number }): string or number
onMoveNode func Called after node move operation.
({ treeData: object[], node: object, treeIndex: number, path: number[] or string[] }): void
onVisibilityToggle func Called after children nodes collapsed or expanded.
({ treeData: object[], node: object, expanded: bool }): void
canDrag func or bool true Return false from callback to prevent node from dragging, by hiding the drag handle. Set prop to false to disable dragging on all nodes.
({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): bool
canDrop func Return 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
reactVirtualizedListProps object Custom properties to hand to the react-virtualized list
rowHeight number or func 62 Used by react-virtualized. Either a fixed row height (number) or a function that returns the height of a row given its index: ({ index: number }): number
slideRegionSize number 100 Size in px of the region near the edges that initiates scrolling on dragover.
scaffoldBlockPxWidth number 44 The width of the blocks containing the lines representing the structure of the tree.
isVirtualized bool true Set to false to disable virtualization. NOTE: Auto-scrolling while dragging, and scrolling to the searchFocusOffset will be disabled.
nodeContentRenderer any NodeRendererDefault Override the default component for rendering nodes (but keep the scaffolding generator) This is an advanced option for complete customization of the appearance. It is best to copy the component in node-renderer-default.js to use as a base, and customize as needed.

Data Helper Functions

Need a hand turning your flat data into nested tree data? Want to perform add/remove operations on the tree data without creating your own recursive function? Check out the helper functions exported from tree-data-utils.js.

Notable among the available functions:

  • getTreeFromFlatData: Convert flat data (like that from a database) into nested tree data
  • getFlatDataFromTree: Convert tree data back to flat data
  • addNodeUnderParent: Add a node under the parent node at the given path
  • removeNodeAtPath: Remove the node at the given path
  • changeNodeAtPath: Modify the node object at the given path
  • map: Perform a change on every node in the tree
  • walk: Visit every node in the tree in order

Documentation for each method is only available in the code at this time. You can also refer to the tests for simple usage examples. If your hobbies happen to include writing documentation, by all means submit a pull request. It would really help out.

Adding External Nodes

How to wrap your own component as an external node

To use your own components as external nodes, you can call dndWrapExternalSource, exported from drag-and-drop-utils.js, like in this example below, as long as you also pass the exact same react-dnd type as set for your tree component, so your custom components can become valid react-dnd DragSources, that can be dropped in to add nodes to your own tree component.

import React, { Component } from 'react'
import { dndWrapExternalSource } from 'react-sortable-tree';

class YourExternalNodeComponent extends Component {

  render() {
    return (<div className='some-class'>{this.props.node.title}</div>);
  }
}


// this will wrap your external node component as a valid react-dnd DragSource
export default dndWrapExternalSource(YourExternalNodeComponent, 'NEW_NODE');

NOTE: You need to implement a dropCancelled method and an addNewItem method, passed as props to your external node component from your parent component, so that your tree-component can effectively respond to your external node. Check out the external node demo for an example implementation. A simple example below:

import React, { Component } from 'react'
import {SortableTree as SortableTreeWithoutDndContext} from 'react-sortable-tree'
import YourExternalNodeComponent from './YourExternalNodeComponent.js'

class App extends Component {
  constructor(props) {
    super(props)

    this.addNewItem = this.addNewItem.bind(this);
    this.dropCancelled = this.dropCancelled.bind(this);
    
    this.state = {
      treeData: [
        { title: 'node1' },
        { title: 'node2' },
      ],
    }
  }

  dropCancelled() {
    // Update the tree appearance post-drag
    this.setState({
      treeData: this.state.treeData.concat(),
    });
  }

  addNewItem(newItem) {
    // insertNode is a helper function from tree-data-utils.js
    const { treeData } = insertNode({
      treeData: this.state.treeData,
      newNode: newItem.node,
      depth: newItem.depth,
      minimumTreeIndex: newItem.minimumTreeIndex,
      expandParent: true,
      getNodeKey: ({ treeIndex }) => treeIndex,
    });
    this.setState({ treeData });
  }
}

render () {
  return (
    <div className='app-container'>
      <div className='tree-container'>
        <SortableTree {...props} />
      </div>
      <div className='external-nodes-container'>
        <YourExternalNodeComponent 
          // just an example external node
          node={{
            title: 'I am a title',
            subtitle: 'some cool subtitle',
          }}
          addNewItem={this.addNewItem}
          dropCancelled={this.dropCancelled}
        />
      </div>
    </div>
  )
}

In addition, the external node wrapper assumes you are using the tree component as SortableTreeWithoutDndContext

Browser Compatibility

Browser Works?
Chrome Yes
Firefox Yes
Safari Yes
IE >= 10 Yes
IE 9 Displays the tree, but drag-and-drop is hit-and-miss

Troubleshooting

If it doesn't work with other components that use react-dnd

react-dnd only allows for one DragDropContext at a time (see: react-dnd/react-dnd#186). To get around this, you can import the context-less tree component via SortableTreeWithoutDndContext.

// before
import SortableTree from 'react-sortable-tree';

// after
import { SortableTreeWithoutDndContext as SortableTree } from 'react-sortable-tree';

Contributing

After cloning the repository and running npm install inside, you can use the following commands to develop and build the project.

# Starts a webpack dev server that hosts a demo page with the component.
# It uses react-hot-loader so changes are reflected on save.
npm start

# This script will start a webpack dev server for the external nodes demo.
npm run external-nodes-demo

# Lints the code with eslint and my custom rules.
npm run lint

# Lints and builds the code, placing the result in the dist directory.
# This build is necessary to reflect changes if you're 
#  `npm link`-ed to this repository from another local project.
npm run build

Pull requests are welcome!

License

MIT