UNPKG

13.3 kBMarkdownView Raw
1# React Sortable Tree
2
3[![NPM](https://nodei.co/npm/react-sortable-tree.png)](https://npmjs.org/package/react-sortable-tree)
4
5[![tree200](https://cloud.githubusercontent.com/assets/4413963/18860410/26f64de8-84b8-11e6-9284-350308eed30a.png)](https://fritz-c.github.io/react-sortable-tree/)
6
7### [Demo](https://fritz-c.github.io/react-sortable-tree/)
8[![demo](https://cloud.githubusercontent.com/assets/4413963/19334888/2be8261c-913a-11e6-9508-4b347ae114b4.gif)](https://fritz-c.github.io/react-sortable-tree/)
9
10### Features
11
12- Works right out of the box, but is highly customizable
13
14## Example
15
16```jsx
17import React, { Component } from 'react';
18import SortableTree from 'react-sortable-tree';
19
20export default class Tree extends Component {
21 constructor(props) {
22 super(props);
23
24 this.state = {
25 treeData: [{ title: 'Chicken', children: [ { title: 'Egg' } ] }],
26 };
27 }
28
29 render() {
30 return (
31 <div style={{ height: 400 }}>
32 <SortableTree
33 treeData={this.state.treeData}
34 onChange={treeData => this.setState({ treeData })}
35 />
36 </div>
37 );
38 }
39}
40
41```
42
43## Options
44
45Property | Type | Default | Required | Description
46:-------------------------|:--------------:|:-------------------:|:--------:|:----------------------------------------
47treeData | object[] | | yes | Tree data with the following keys: <div>`title` is the primary label for the node.</div><div>`subtitle` is a secondary label for the node.</div><div>`expanded` shows children of the node if true, or hides them if false. Defaults to false.</div><div>`children` is an array of child nodes belonging to the node.</div><div>__Example__: `[{title: 'main', subtitle: 'sub'}, { title: 'value2', expanded: true, children: [{ title: 'value3') }] }]`
48onChange | 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.<div>`( treeData: object[] ): void`</div>
49style | object | `{}` | | Style applied to the container wrapping the tree (style defaults to {height: '100%'})
50className | string | | | Class name for the container wrapping the tree
51dndType | string | | | String value used by [react-dnd](http://react-dnd.github.io/react-dnd/docs-overview.html) (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
52innerStyle | object | `{}` | | Style applied to the inner, scrollable container (for padding, etc.)
53maxDepth | number | | | Maximum depth nodes can be inserted at. Defaults to infinite.
54searchMethod | 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.<div>`({ node: object, path: number[] or string[], treeIndex: number, searchQuery: any }): bool`</div>
55searchQuery | 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.
56searchFocusOffset | number | | | Outline the <`searchFocusOffset`>th node and scroll to it.
57searchFinishCallback | func | | | Get the nodes that match the search criteria. Used for counting total matches, etc.<div>`(matches: { node: object, path: number[] or string[], treeIndex: number }[]): void`</div>
58generateNodeProps | 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.<div>`({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): object`</div>
59getNodeKey | 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).<div>`({ node: object, treeIndex: number }): string or number`</div>
60onMoveNode | func | | | Called after node move operation. <div>`({ treeData: object[], node: object, treeIndex: number, path: number[] or string[] }): void`</div>
61onVisibilityToggle | func | | | Called after children nodes collapsed or expanded. <div>`({ treeData: object[], node: object, expanded: bool }): void`</div>
62canDrag | 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. <div>`({ node: object, path: number[] or string[], treeIndex: number, lowerSiblingCounts: number[], isSearchMatch: bool, isSearchFocus: bool }): bool`</div>
63canDrop | func | | | Return false to prevent node from dropping in the given location. <div>`({ node: object, prevPath: number[] or string[], prevParent: object, prevTreeIndex: number, nextPath: number[] or string[], nextParent: object, nextTreeIndex: number}): bool`</div>
64reactVirtualizedListProps | object | | | Custom properties to hand to the [react-virtualized list](https://github.com/bvaughn/react-virtualized/blob/master/docs/List.md#prop-types)
65rowHeight | 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`
66slideRegionSize | number | `100` | | Size in px of the region near the edges that initiates scrolling on dragover.
67scaffoldBlockPxWidth | number | `44` | | The width of the blocks containing the lines representing the structure of the tree.
68isVirtualized | bool | `true` | | Set to false to disable virtualization. __NOTE__: Auto-scrolling while dragging, and scrolling to the `searchFocusOffset` will be disabled.
69nodeContentRenderer | 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.
70
71## Data Helper Functions
72
73Need a hand turning your flat data into nested tree data?
74Want to perform add/remove operations on the tree data without creating your own recursive function?
75Check out the helper functions exported from [`tree-data-utils.js`](https://github.com/fritz-c/react-sortable-tree/blob/master/src/utils/tree-data-utils.js).
76
77Notable among the available functions:
78
79- __`getTreeFromFlatData`__: Convert flat data (like that from a database) into nested tree data
80- __`getFlatDataFromTree`__: Convert tree data back to flat data
81- __`addNodeUnderParent`__: Add a node under the parent node at the given path
82- __`removeNodeAtPath`__: Remove the node at the given path
83- __`changeNodeAtPath`__: Modify the node object at the given path
84- __`map`__: Perform a change on every node in the tree
85- __`walk`__: Visit every node in the tree in order
86
87Documentation for each method is only available in the code at this time. You can also refer to the tests for simple usage examples.
88If your hobbies happen to include writing documentation, by all means submit a pull request. It would really help out.
89
90## Adding External Nodes
91
92### How to wrap your own component as an external node
93
94To use your own components as external nodes, you can call `dndWrapExternalSource`, exported from [`drag-and-drop-utils.js`](https://github.com/fritz-c/react-sortable-tree/blob/master/src/utils/drag-and-drop-utils.js), like in this example below, as long as you also pass the exact same [react-dnd type](http://react-dnd.github.io/react-dnd/docs-overview.html) as set for your tree component, so your custom components can become valid react-dnd [DragSources](http://react-dnd.github.io/react-dnd/docs-drag-source.html), that can be dropped in to add nodes to your own tree component.
95
96```jsx
97import React, { Component } from 'react'
98import { dndWrapExternalSource } from 'react-sortable-tree';
99
100class YourExternalNodeComponent extends Component {
101
102 render() {
103 return (<div className='some-class'>{this.props.node.title}</div>);
104 }
105}
106
107
108// this will wrap your external node component as a valid react-dnd DragSource
109export default dndWrapExternalSource(YourExternalNodeComponent, 'NEW_NODE');
110```
111
112__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:
113
114```jsx
115import React, { Component } from 'react'
116import {SortableTree as SortableTreeWithoutDndContext} from 'react-sortable-tree'
117import YourExternalNodeComponent from './YourExternalNodeComponent.js'
118
119class App extends Component {
120 constructor(props) {
121 super(props)
122
123 this.addNewItem = this.addNewItem.bind(this);
124 this.dropCancelled = this.dropCancelled.bind(this);
125
126 this.state = {
127 treeData: [
128 { title: 'node1' },
129 { title: 'node2' },
130 ],
131 }
132 }
133
134 dropCancelled() {
135 // Update the tree appearance post-drag
136 this.setState({
137 treeData: this.state.treeData.concat(),
138 });
139 }
140
141 addNewItem(newItem) {
142 // insertNode is a helper function from tree-data-utils.js
143 const { treeData } = insertNode({
144 treeData: this.state.treeData,
145 newNode: newItem.node,
146 depth: newItem.depth,
147 minimumTreeIndex: newItem.minimumTreeIndex,
148 expandParent: true,
149 getNodeKey: ({ treeIndex }) => treeIndex,
150 });
151 this.setState({ treeData });
152 }
153}
154
155render () {
156 return (
157 <div className='app-container'>
158 <div className='tree-container'>
159 <SortableTree {...props} />
160 </div>
161 <div className='external-nodes-container'>
162 <YourExternalNodeComponent
163 // just an example external node
164 node={{
165 title: 'I am a title',
166 subtitle: 'some cool subtitle',
167 }}
168 addNewItem={this.addNewItem}
169 dropCancelled={this.dropCancelled}
170 />
171 </div>
172 </div>
173 )
174}
175
176```
177
178
179In addition, the external node wrapper assumes you are using the tree component as `SortableTreeWithoutDndContext`
180
181
182## Browser Compatibility
183
184| Browser | Works? |
185|:-----|:-----|
186| Chrome | Yes |
187| Firefox | Yes |
188| Safari | Yes |
189| IE >= 10 | Yes |
190| IE 9 | Displays the tree, but drag-and-drop is hit-and-miss |
191
192## Troubleshooting
193
194### If it doesn't work with other components that use react-dnd
195
196react-dnd only allows for one DragDropContext at a time (see: https://github.com/gaearon/react-dnd/issues/186). To get around this, you can import the context-less tree component via `SortableTreeWithoutDndContext`.
197```js
198// before
199import SortableTree from 'react-sortable-tree';
200
201// after
202import { SortableTreeWithoutDndContext as SortableTree } from 'react-sortable-tree';
203```
204
205## Contributing
206
207After cloning the repository and running `npm install` inside, you can use the following commands to develop and build the project.
208
209```sh
210# Starts a webpack dev server that hosts a demo page with the component.
211# It uses react-hot-loader so changes are reflected on save.
212npm start
213
214# This script will start a webpack dev server for the external nodes demo.
215npm run external-nodes-demo
216
217# Lints the code with eslint and my custom rules.
218npm run lint
219
220# Lints and builds the code, placing the result in the dist directory.
221# This build is necessary to reflect changes if you're
222# `npm link`-ed to this repository from another local project.
223npm run build
224```
225
226Pull requests are welcome!
227
228## License
229
230MIT