Convert Figma logo to code with AI

frontend-collective logoreact-sortable-tree

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

4,894
897
4,894
340

Top Related Projects

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

Beautiful and accessible drag and drop for lists with React

20,973

Drag and Drop for React

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

10,773

Infinite responsive, sortable, filterable and draggable layouts

21,948

:ok_hand: Drag and drop so simple it hurts

Quick Overview

React Sortable Tree is a React component for creating drag-and-drop sortable and nestable lists. It provides a flexible and customizable tree structure that can be used for various applications, such as file explorers, category management, or hierarchical data representation.

Pros

  • Easy to integrate with React applications
  • Highly customizable with various styling and behavior options
  • Supports both vertical and horizontal layouts
  • Includes built-in keyboard navigation for accessibility

Cons

  • Learning curve for advanced customization
  • Performance may degrade with very large trees
  • Limited built-in theming options
  • Requires additional setup for server-side rendering

Code Examples

  1. Basic usage:
import SortableTree from 'react-sortable-tree';

const treeData = [
  { title: 'Chicken', children: [{ title: 'Egg' }] },
  { title: 'Fish', children: [{ title: 'fingerling' }] },
];

const MyComponent = () => (
  <div style={{ height: 400 }}>
    <SortableTree
      treeData={treeData}
      onChange={treeData => console.log(treeData)}
    />
  </div>
);
  1. Custom node rendering:
import SortableTree, { TreeItem } from 'react-sortable-tree';

const MyComponent = () => (
  <SortableTree
    treeData={treeData}
    generateNodeProps={({ node, path }) => ({
      title: (
        <span style={{ color: node.color }}>
          {node.title}
        </span>
      ),
    })}
  />
);
  1. Adding external nodes:
import SortableTree, { addNodeUnderParent } from 'react-sortable-tree';

const MyComponent = () => {
  const [treeData, setTreeData] = useState(initialData);

  const addNode = () => {
    const newTree = addNodeUnderParent({
      treeData,
      parentKey: null,
      expandParent: true,
      getNodeKey: ({ node }) => node.id,
      newNode: { id: '123', title: 'New Node' },
    }).treeData;

    setTreeData(newTree);
  };

  return (
    <>
      <button onClick={addNode}>Add Node</button>
      <SortableTree treeData={treeData} onChange={setTreeData} />
    </>
  );
};

Getting Started

  1. Install the package:

    npm install react-sortable-tree
    
  2. Import and use in your React component:

    import React, { useState } from 'react';
    import SortableTree from 'react-sortable-tree';
    import 'react-sortable-tree/style.css';
    
    const MyTreeComponent = () => {
      const [treeData, setTreeData] = useState([
        { title: 'Node 1', children: [{ title: 'Child 1' }] },
        { title: 'Node 2' },
      ]);
    
      return (
        <div style={{ height: 400 }}>
          <SortableTree
            treeData={treeData}
            onChange={treeData => setTreeData(treeData)}
          />
        </div>
      );
    };
    
    export default MyTreeComponent;
    

Competitor Comparisons

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

Pros of react-sortable-hoc

  • More flexible and can be used with various components, not limited to tree structures
  • Lighter weight and potentially better performance for simpler sorting tasks
  • Easier to integrate with existing React components and lists

Cons of react-sortable-hoc

  • Lacks built-in tree structure support, requiring more custom implementation for hierarchical data
  • May require more setup and configuration for complex sorting scenarios
  • Doesn't provide as many out-of-the-box features specific to tree manipulation

Code Comparison

react-sortable-tree:

import SortableTree from 'react-sortable-tree';

<SortableTree
  treeData={this.state.treeData}
  onChange={treeData => this.setState({ treeData })}
/>

react-sortable-hoc:

import { SortableContainer, SortableElement } from 'react-sortable-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${index}`} index={index} value={value} />
      ))}
    </ul>
  );
});

The code comparison shows that react-sortable-tree provides a more straightforward implementation for tree structures, while react-sortable-hoc requires more setup but offers greater flexibility for various list types.

Beautiful and accessible drag and drop for lists with React

Pros of react-beautiful-dnd

  • More intuitive and accessible drag-and-drop experience
  • Better performance for large lists and complex layouts
  • Extensive documentation and community support

Cons of react-beautiful-dnd

  • Limited to vertical lists and horizontal lists; no support for tree structures
  • Less flexibility in customizing drag handles and drop targets
  • Steeper learning curve for complex implementations

Code Comparison

react-beautiful-dnd:

<DragDropContext onDragEnd={onDragEnd}>
  <Droppable droppableId="list">
    {(provided) => (
      <ul {...provided.droppableProps} ref={provided.innerRef}>
        {items.map((item, index) => (
          <Draggable key={item.id} draggableId={item.id} index={index}>
            {(provided) => (
              <li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                {item.content}
              </li>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </ul>
    )}
  </Droppable>
</DragDropContext>

react-sortable-tree:

<SortableTree
  treeData={treeData}
  onChange={(treeData) => this.setState({ treeData })}
  generateNodeProps={({ node, path }) => ({
    title: node.title,
    subtitle: node.subtitle,
  })}
/>

react-beautiful-dnd offers a more declarative API with separate components for different drag-and-drop elements, while react-sortable-tree provides a more compact and tree-specific implementation.

20,973

Drag and Drop for React

Pros of react-dnd

  • More flexible and customizable for complex drag-and-drop interactions
  • Supports a wider range of use cases beyond tree structures
  • Larger community and ecosystem with more resources and extensions

Cons of react-dnd

  • Steeper learning curve and more complex implementation for basic use cases
  • Requires more boilerplate code to set up drag-and-drop functionality
  • Less out-of-the-box functionality for tree-like structures

Code Comparison

react-dnd:

import { useDrag, useDrop } from 'react-dnd';

function DraggableItem({ id, text }) {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'ITEM',
    item: { id },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  return <div ref={drag}>{text}</div>;
}

react-sortable-tree:

import SortableTree from 'react-sortable-tree';

function TreeComponent({ treeData, onChange }) {
  return (
    <SortableTree
      treeData={treeData}
      onChange={onChange}
      generateNodeProps={({ node }) => ({
        title: node.title,
      })}
    />
  );
}

react-sortable-tree provides a more straightforward implementation for tree structures, while react-dnd offers greater flexibility but requires more setup code.

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

Pros of Sortable

  • Framework-agnostic, works with vanilla JavaScript and various frameworks
  • Supports more diverse drag-and-drop scenarios (lists, grids, nested structures)
  • Smaller bundle size and potentially better performance

Cons of Sortable

  • Requires more setup and configuration for complex tree structures
  • Less specialized for tree-like data structures
  • May need additional work to achieve the same level of tree functionality as react-sortable-tree

Code Comparison

react-sortable-tree:

import SortableTree from 'react-sortable-tree';

<SortableTree
  treeData={this.state.treeData}
  onChange={treeData => this.setState({ treeData })}
/>

Sortable:

import Sortable from 'sortablejs';

Sortable.create(document.getElementById('tree'), {
  group: 'nested',
  animation: 150,
  fallbackOnBody: true,
  swapThreshold: 0.65
});

While react-sortable-tree provides a more declarative API specifically for tree structures, Sortable offers a more flexible approach that can be adapted to various scenarios, including trees, with additional configuration.

10,773

Infinite responsive, sortable, filterable and draggable layouts

Pros of Muuri

  • Framework-agnostic: Works with any JavaScript framework or vanilla JS
  • Flexible layout options: Supports grid, list, and custom layouts
  • Lightweight: Smaller bundle size compared to React Sortable Tree

Cons of Muuri

  • Less specialized for tree structures: Requires more custom implementation for hierarchical data
  • No built-in React integration: Needs additional wrapper or hooks for React projects
  • Steeper learning curve: More configuration options can increase complexity

Code Comparison

React Sortable Tree:

import SortableTree from 'react-sortable-tree';

<SortableTree
  treeData={this.state.treeData}
  onChange={treeData => this.setState({ treeData })}
/>

Muuri:

import Muuri from 'muuri';

const grid = new Muuri('.grid', {
  dragEnabled: true,
  layoutOnInit: false
});

grid.layout();

Both libraries offer drag-and-drop functionality, but React Sortable Tree is specifically designed for tree structures, while Muuri provides more general-purpose sorting and layout capabilities. React Sortable Tree integrates seamlessly with React applications, whereas Muuri requires additional setup for React integration but offers more flexibility across different frameworks.

21,948

:ok_hand: Drag and drop so simple it hurts

Pros of dragula

  • Framework-agnostic: Works with any JavaScript framework or vanilla JS
  • Lightweight: Smaller bundle size and fewer dependencies
  • Flexible: Can be used for various drag-and-drop scenarios beyond tree structures

Cons of dragula

  • Less specialized: Requires more custom code for tree-specific functionality
  • Limited built-in features: Lacks advanced tree operations like node expansion/collapse
  • Manual state management: Requires additional effort to maintain tree state

Code Comparison

dragula:

dragula([document.querySelector('#left-defaults'), document.querySelector('#right-defaults')])
  .on('drag', function(el) {
    el.className = el.className.replace('ex-moved', '');
  }).on('drop', function(el) {
    el.className += ' ex-moved';
  });

react-sortable-tree:

import SortableTree from 'react-sortable-tree';

<SortableTree
  treeData={this.state.treeData}
  onChange={treeData => this.setState({ treeData })}
  generateNodeProps={rowInfo => ({
    buttons: [<button onClick={() => this.removeNode(rowInfo)}>X</button>],
  })}
/>

The code examples demonstrate the different approaches: dragula requires more manual setup and event handling, while react-sortable-tree provides a more declarative and tree-specific API out of the box.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Note on maintenance

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

React Sortable Tree

NPM version NPM license NPM total downloads NPM monthly downloads Build Status Coverage Status PRs Welcome

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

Table of Contents

Getting started

Install react-sortable-tree using npm.

# NPM
npm install react-sortable-tree --save

# YARN
yarn 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 context
import SortableTree from 'react-sortable-tree';

// Or you can import the tree without the dnd context as a named export. eg
import { SortableTreeWithoutDndContext as SortableTree } from 'react-sortable-tree';

// Importing from cjs (default)
import SortableTree from 'react-sortable-tree/dist/index.cjs.js';
import SortableTree from 'react-sortable-tree';

// Importing from esm
import SortableTree from 'react-sortable-tree/dist/index.esm.js';

Usage

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 Tree extends Component {
  constructor(props) {
    super(props);

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

  render() {
    return (
      <div style={{ height: 400 }}>
        <SortableTree
          treeData={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 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 true. NOTE: 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.

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.

  • 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 the theme 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 (only two 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 my file 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 at create-react-app#2376.

The simplest way to mitigate this issue is by adding comparisons: 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: https://github.com/gaearon/react-dnd/issues/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

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

After cloning the repository and running yarn 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 tests
yarn test

# Lints the code with eslint
yarn 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

NPM DownloadsLast 30 Days