Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

frontend-collective/react-sortable-tree

Repository files navigation

This library is not actively maintained.Please find and discuss alternatives here.

React Sortable Tree

NPM versionNPM licenseNPM total downloadsNPM monthly downloadsBuild StatusCoverage StatusPRs Welcome

A React component for Drag-and-drop sortable representation of hierarchical data. Checkout theStorybook for a demonstration of some basic and advanced features.

Table of Contents

Getting started

Installreact-sortable-tree using npm.

# NPMnpm install react-sortable-tree --save# YARNyarn add react-sortable-tree

ES6 and CommonJS builds are available with each distribution.For example:

// This only needs to be done once; probably during your application's bootstrapping process.import'react-sortable-tree/style.css';// You can import the default tree with dnd contextimportSortableTreefrom'react-sortable-tree';// Or you can import the tree without the dnd context as a named export. egimport{SortableTreeWithoutDndContextasSortableTree}from'react-sortable-tree';// Importing from cjs (default)importSortableTreefrom'react-sortable-tree/dist/index.cjs.js';importSortableTreefrom'react-sortable-tree';// Importing from esmimportSortableTreefrom'react-sortable-tree/dist/index.esm.js';

Usage

importReact,{Component}from'react';importSortableTreefrom'react-sortable-tree';import'react-sortable-tree/style.css';// This only needs to be imported once in your appexportdefaultclassTreeextendsComponent{constructor(props){super(props);this.state={treeData:[{title:'Chicken',children:[{title:'Egg'}]},{title:'Fish',children:[{title:'fingerline'}]},],};}render(){return(<divstyle={{height:400}}><SortableTreetreeData={this.state.treeData}onChange={treeData=>this.setState({ treeData})}/></div>);}}

Props

PropType
Description
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 thepath array passed in callbacks. With a setting ofgetNodeKey={({ node }) => node.id}, for example, in callbacks this will let you easily determine that the node with anid of35 is (or has just become) a child of the node with anid of12, which is a child of ... and so on. It usesdefaultGetNodeKey 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 thebuttons key, or additionalstyle /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 tofalse to disable dragging on all nodes. Defaults totrue.
({ 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 acanDrop condition. Default is set to a function that returnstrue. Functions should be of type(node): bool.
themeobjectSet an all-in-one packaged appearance for the tree. See theThemes section for more information.
searchMethodfuncThe method used to search nodes. Defaults todefaultSearchMethod, which uses thesearchQuery string to search for nodes with matchingtitle orsubtitle values. NOTE: ChangingsearchMethod will not update the search, but changing thesearchQuery will.
({ node: object, path: number[] or string[], treeIndex: number, searchQuery: any }): bool
searchQuerystring or anyUsed by thesearchMethod to highlight and scroll to matched nodes. Should be a string for the defaultsearchMethod, but can be anything when using a custom search. Defaults tonull.
searchFocusOffsetnumberOutline the <searchFocusOffset>th node and scroll to it.
onlyExpandSearchedNodesbooleanOnly expand the nodes that match searches. Collapses all other nodes. Defaults tofalse.
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 byreact-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 tofalse.
({ node: object, prevPath: number[] or string[], prevTreeIndex: number, }): bool
reactVirtualizedListPropsobjectCustom properties to hand to the internalreact-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 to62. 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 to100.
scaffoldBlockPxWidthnumberThe width of the blocks containing the lines representing the structure of the tree. Defaults to44.
isVirtualizedboolSet to false to disable virtualization. Defaults totrue.NOTE: Auto-scrolling while dragging, and scrolling to thesearchFocusOffset 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 withgenerateNodeProps, atheme or CSS rules. If you must use it, is best to copy the component innode-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 atheme or custom CSS instead.

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 fromtree-data-utils.js.

  • 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.
  • removeNode: For a given path, get the node at that path, treeIndex, and the treeData with that node removed.
  • removeNodeAtPath: For a given path, remove the node and return the treeData.
  • 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.
  • getDescendantCount: Count how many descendants this node has.
  • getVisibleNodeCount: Count how many visible descendants this node has.
  • getVisibleNodeInfoAtIndex: Get the th visible node in the tree data.
  • toggleExpandedForAll: Expand or close every node in the tree.
  • getNodeAtPath: Get the node at the input path.
  • insertNode: Insert the input node at the specified depth and minimumTreeIndex.
  • find: Find nodes matching a search query in the tree.
  • isDescendant: Check if a node is a descendant of another node.
  • getDepth: Get the longest path in the tree.

Themes

Using thetheme prop along with an imported theme module, you can easily override the default appearance with another standard one.

Featured themes

File Explorer ThemeFull Node Drag ThemeMINIMAL THEME
File ExplorerFull Node DragMinimalistic theme inspired from MATERIAL UI
react-sortable-tree-theme-file-explorerreact-sortable-tree-theme-full-node-dragreact-sortable-tree-theme-minimal
Github |NPMGithub |NPMGithub |NPM

Help Wanted - As the themes feature has just been enabled, there are very few (onlytwo at the time of this writing) theme modules available. If you've customized the appearance of your tree to be especially cool or easy to use, I would be happy to feature it in this readme with a link to the Github repo and NPM page if you convert it to a theme. You can use myfile explorer theme repo as a template to plug in your own stuff.

Browser Compatibility

BrowserWorks?
ChromeYes
FirefoxYes
SafariYes
IE 11Yes

Troubleshooting

If it throws "TypeError: fn is not a function" errors in production

This issue may be related to an ongoing incompatibility between UglifyJS and Webpack's behavior. See an explanation atcreate-react-app#2376.

The simplest way to mitigate this issue is by addingcomparisons: false to your Uglify config as seen here:https://github.com/facebookincubator/create-react-app/pull/2379/files

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 viaSortableTreeWithoutDndContext.

// beforeimportSortableTreefrom'react-sortable-tree';// afterimport{SortableTreeWithoutDndContextasSortableTree}from'react-sortable-tree';

Contributing

Please read theCode of Conduct. I actively welcome pull requests :)

After cloning the repository and runningyarn 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.yarn start# Start the storybook, which has several different examples to play with.# Also hot-reloaded.yarn run storybook# Runs the library testsyarntest# Lints the code with eslintyarn 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.yarn run build

Pull requests are welcome!

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp