react-sortable-hoc vs react-sortable-tree
Drag-and-Drop Sorting Libraries for React Applications
react-sortable-hocreact-sortable-treeSimilar Packages:
Drag-and-Drop Sorting Libraries for React Applications

react-sortable-hoc and react-sortable-tree are both React libraries that enable drag-and-drop reordering of UI elements, but they target fundamentally different use cases. react-sortable-hoc is a general-purpose higher-order component (HOC) utility that adds sortable behavior to any list or grid of items by wrapping existing components. In contrast, react-sortable-tree is a specialized component built specifically for rendering and manipulating hierarchical tree structures with nested nodes, complete with built-in UI for expand/collapse, depth indicators, and subtree reordering.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
react-sortable-hoc675,09510,900-2915 years agoMIT
react-sortable-tree52,3284,978-3516 years agoMIT

react-sortable-hoc vs react-sortable-tree: Choosing the Right Drag-and-Drop Sorting Tool

Both react-sortable-hoc and react-sortable-tree bring drag-and-drop reordering to React apps, but they solve very different problems. One is a flexible utility for making any list sortable; the other is a ready-made tree component with built-in hierarchy management. Let’s break down how they work, what they’re good for, and why neither should be used in new projects.

⚠️ Deprecation Status: Critical First Consideration

Both packages are officially deprecated.

  • react-sortable-hoc shows a clear deprecation notice on its npm page and GitHub repository, recommending migration to @dnd-kit/sortable.
  • react-sortable-tree has been archived on GitHub and marked as unmaintained, with no updates in years.

Important: For new projects, avoid both. Use modern, actively maintained alternatives. This comparison is provided for legacy code maintenance or architectural understanding only.

🧩 Core Purpose: General Utility vs Specialized Component

react-sortable-hoc is a set of higher-order components that inject drag-and-drop sorting logic into your existing React components. You keep full control over rendering.

// react-sortable-hoc: Wrap your own item component
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>
  );
});

// Usage
<SortableList items={['Apple', 'Banana', 'Cherry']} onSortEnd={handleSort} />

react-sortable-tree is a complete, self-contained tree component. You pass it data, and it renders the entire interactive hierarchy.

// react-sortable-tree: Provide tree data, get a ready-made UI
import SortableTree from 'react-sortable-tree';

const treeData = [
  { title: 'Parent', children: [
    { title: 'Child 1' },
    { title: 'Child 2' }
  ]}
];

<SortableTree
  treeData={treeData}
  onChange={newTree => console.log(newTree)}
  canDrag={true}
/>

🗂️ Data Structure: Flat Lists vs Nested Trees

react-sortable-hoc works with flat arrays. It doesn’t understand hierarchy — each item is independent.

// Input for react-sortable-hoc
const items = ['Item A', 'Item B', 'Item C']; // flat array

react-sortable-tree requires a recursive tree structure with children arrays.

// Input for react-sortable-tree
const treeData = [
  {
    title: 'Node 1',
    children: [
      { title: 'Leaf A' },
      { title: 'Leaf B' }
    ]
  }
];

You cannot use react-sortable-hoc to build a collapsible tree without significant custom logic. Conversely, react-sortable-tree cannot render a simple flat list without unnecessary overhead.

🎨 Rendering Control: Full Freedom vs Locked-In UI

With react-sortable-hoc, you define every aspect of how items look. The HOC only handles drag state and position updates.

// Fully custom item rendering
const SortableItem = SortableElement(({ user }) => (
  <div className="user-card">
    <img src={user.avatar} />
    <span>{user.name}</span>
  </div>
));

react-sortable-tree gives you limited customization via props like rowHeight, generateNodeProps, or theme, but the core layout (indentation, collapse buttons, connectors) is fixed.

// Limited customization in react-sortable-tree
<SortableTree
  generateNodeProps={({ node }) => ({
    style: { color: node.isSpecial ? 'red' : 'black' }
  })}
/>

If you need pixel-perfect control over item appearance or non-standard layouts (e.g., masonry grids), react-sortable-hoc is more adaptable — though again, it’s deprecated.

🔄 State Management: Manual vs Built-In

react-sortable-hoc leaves state management entirely to you. You receive an onSortEnd callback with old/new indices and must update your data accordingly.

function handleSortEnd({ oldIndex, newIndex }) {
  const newItems = arrayMove(items, oldIndex, newIndex);
  setItems(newItems); // you manage the state
}

react-sortable-tree manages the entire tree state internally and calls onChange with the new tree structure whenever it changes.

function handleChange(treeData) {
  setTreeData(treeData); // treeData is the full new tree
}

The tree component handles complex operations like moving a node between different parents or depths automatically. With react-sortable-hoc, you’d have to implement cross-container or nested logic yourself.

🖱️ Interaction Model: Simple Reordering vs Hierarchical Manipulation

react-sortable-hoc supports:

  • Reordering within a single list
  • Dragging between multiple lists (with additional setup)
  • Horizontal or vertical orientation

But it does not support:

  • Nesting items under others
  • Collapsing/expanding sections
  • Visual depth indicators

react-sortable-tree supports:

  • Dragging nodes to become children of other nodes
  • Collapsing/expanding subtrees
  • Visual indentation and connection lines
  • Programmatic expansion control

But it does not support:

  • Non-hierarchical layouts
  • Custom drag previews beyond basic theming
  • Fine-grained control over drop zones

🧪 Real-World Fit: When Each Makes (Legacy) Sense

Use react-sortable-hoc (legacy only) if:

  • You have a flat list of cards, images, or form fields to reorder
  • You already have styled components and just need DnD behavior added
  • You need to integrate sorting into an existing complex layout

Example: Reordering steps in a workflow builder where each step is a custom React component.

Use react-sortable-tree (legacy only) if:

  • You’re building a file explorer, org chart, or category manager
  • You need users to restructure nested data visually
  • You want built-in collapse/expand without writing it yourself

Example: An admin panel for managing a product taxonomy with drag-and-drop category nesting.

🔁 Modern Alternatives to Consider

Since both packages are deprecated, here are current options:

📊 Summary: Key Differences

Featurereact-sortable-hocreact-sortable-tree
Primary Use CaseFlat lists, grids, custom layoutsNested hierarchical trees
Rendering ControlFull — you provide all JSXLimited — built-in UI with theming
Data StructureFlat arrayRecursive tree with children
Hierarchy Support❌ No✅ Yes (drag to nest, collapse, etc.)
Maintenance Status❌ Deprecated❌ Deprecated
Best For (Legacy)Adding DnD to existing flat componentsOut-of-the-box interactive tree UI

💡 Final Guidance

Don’t start new projects with either library. Their deprecation isn’t just about missing features — it means no security updates, bug fixes, or compatibility with future React versions (especially concurrent features).

For flat sorting, @dnd-kit/sortable offers a cleaner, hook-based API with better accessibility. For trees, evaluate whether you truly need a full interactive tree component or if a simpler custom solution using a modern DnD library would suffice.

Understanding these two packages helps when maintaining older codebases, but forward-looking architecture demands modern, supported tools.

How to Choose: react-sortable-hoc vs react-sortable-tree
  • react-sortable-hoc:

    Choose react-sortable-hoc when you need to add drag-and-drop sorting to flat lists, grids, or custom layouts using your own components. It’s ideal for scenarios like reordering dashboard widgets, photo galleries, or task lists where you want full control over rendering and minimal opinionated UI. However, note that the package is officially deprecated and should be avoided in new projects; consider modern alternatives like @dnd-kit/sortable instead.

  • react-sortable-tree:

    Choose react-sortable-tree only if you specifically need an interactive, nested tree structure with drag-and-drop reordering of nodes across different depths. It provides out-of-the-box UI for indentation, collapse/expand toggles, and connection lines. Be aware that this package is also deprecated and unmaintained — for new projects requiring tree-based sorting, evaluate actively maintained libraries such as react-arborist or react-sortable-tree-v2 (community fork), or build a custom solution using lower-level DnD primitives.

README for react-sortable-hoc

React Sortable HOC

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

npm version npm downloads license Gitter gzip size

Examples available here: http://clauderic.github.io/react-sortable-hoc/

Features

  • Higher Order Components – Integrates with your existing components
  • Drag handle, auto-scrolling, locked axis, events, and more!
  • Suuuper smooth animations – Chasing the 60FPS dream 🌈
  • Works with virtualization libraries: react-virtualized, react-tiny-virtual-list, react-infinite, etc.
  • Horizontal lists, vertical lists, or a grid ↔ ↕ ⤡
  • Touch support 👌
  • Accessible: supports keyboard sorting

Installation

Using npm:

$ npm install react-sortable-hoc --save

Then, using a module bundler that supports either CommonJS or ES2015 modules, such as webpack:

// Using an ES6 transpiler like Babel
import {SortableContainer, SortableElement} from 'react-sortable-hoc';

// Not using an ES6 transpiler
var Sortable = require('react-sortable-hoc');
var SortableContainer = Sortable.SortableContainer;
var SortableElement = Sortable.SortableElement;

Alternatively, an UMD build is also available:

<script src="react-sortable-hoc/dist/react-sortable-hoc.umd.js"></script>

Usage

Basic Example

import React, {Component} from 'react';
import {render} from 'react-dom';
import {SortableContainer, SortableElement} from 'react-sortable-hoc';
import arrayMove from 'array-move';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);

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

class SortableComponent extends Component {
  state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
  };
  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState(({items}) => ({
      items: arrayMove(items, oldIndex, newIndex),
    }));
  };
  render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
  }
}

render(<SortableComponent />, document.getElementById('root'));

That's it! React Sortable does not come with any styles by default, since it's meant to enhance your existing components.

More code examples are available here.

Why should I use this?

There are already a number of great Drag & Drop libraries out there (for instance, react-dnd is fantastic). If those libraries fit your needs, you should definitely give them a try first. However, most of those libraries rely on the HTML5 Drag & Drop API, which has some severe limitations. For instance, things rapidly become tricky if you need to support touch devices, if you need to lock dragging to an axis, or want to animate the nodes as they're being sorted. React Sortable HOC aims to provide a simple set of higher-order components to fill those gaps. If you're looking for a dead-simple, mobile-friendly way to add sortable functionality to your lists, then you're in the right place.

Prop Types

SortableContainer HOC

PropertyTypeDefaultDescription
axisStringyItems can be sorted horizontally, vertically or in a grid. Possible values: x, y or xy
lockAxisStringIf you'd like, you can lock movement to an axis while sorting. This is not something that is possible with HTML5 Drag & Drop. Possible values: x or y.
helperClassStringYou can provide a class you'd like to add to the sortable helper to add some styles to it
transitionDurationNumber300The duration of the transition when elements shift positions. Set this to 0 if you'd like to disable transitions
keyboardSortingTransitionDurationNumbertransitionDurationThe duration of the transition when the helper is shifted during keyboard sorting. Set this to 0 if you'd like to disable transitions for the keyboard sorting helper. Defaults to the value set for transitionDuration if undefined
keyCodesArray{
  lift: [32],
  drop: [32],
  cancel: [27],
  up: [38, 37],
  down: [40, 39]
}
An object containing an array of keycodes for each keyboard-accessible action.
pressDelayNumber0If you'd like elements to only become sortable after being pressed for a certain time, change this property. A good sensible default value for mobile is 200. Cannot be used in conjunction with the distance prop.
pressThresholdNumber5Number of pixels of movement to tolerate before ignoring a press event.
distanceNumber0If you'd like elements to only become sortable after being dragged a certain number of pixels. Cannot be used in conjunction with the pressDelay prop.
shouldCancelStartFunctionFunctionThis function is invoked before sorting begins, and can be used to programatically cancel sorting before it begins. By default, it will cancel sorting if the event target is either an input, textarea, select, option, or button.
updateBeforeSortStartFunctionThis function is invoked before sorting begins. It can return a promise, allowing you to run asynchronous updates (such as setState) before sorting begins. function({node, index, collection, isKeySorting}, event)
onSortStartFunctionCallback that is invoked when sorting begins. function({node, index, collection, isKeySorting}, event)
onSortMoveFunctionCallback that is invoked during sorting as the cursor moves. function(event)
onSortOverFunctionCallback that is invoked when moving over an item. function({index, oldIndex, newIndex, collection, isKeySorting}, e)
onSortEndFunctionCallback that is invoked when sorting ends. function({oldIndex, newIndex, collection, isKeySorting}, e)
useDragHandleBooleanfalseIf you're using the SortableHandle HOC, set this to true
useWindowAsScrollContainerBooleanfalseIf you want, you can set the window as the scrolling container
hideSortableGhostBooleantrueWhether to auto-hide the ghost element. By default, as a convenience, React Sortable List will automatically hide the element that is currently being sorted. Set this to false if you would like to apply your own styling.
lockToContainerEdgesBooleanfalseYou can lock movement of the sortable element to it's parent SortableContainer
lockOffsetOffsetValue* | [OffsetValue*, OffsetValue*]"50%"WhenlockToContainerEdgesis set totrue, this controls the offset distance between the sortable helper and the top/bottom edges of it's parentSortableContainer. Percentage values are relative to the height of the item currently being sorted. If you wish to specify different behaviours for locking to the top of the container vs the bottom, you may also pass in anarray(For example:["0%", "100%"]).
getContainerFunctionOptional function to return the scrollable container element. This property defaults to the SortableContainer element itself or (if useWindowAsScrollContainer is true) the window. Use this function to specify a custom container object (eg this is useful for integrating with certain 3rd party components such as FlexTable). This function is passed a single parameter (the wrappedInstance React element) and it is expected to return a DOM element.
getHelperDimensionsFunctionFunctionOptional function({node, index, collection}) that should return the computed dimensions of the SortableHelper. See default implementation for more details
helperContainerHTMLElement | Functiondocument.bodyBy default, the cloned sortable helper is appended to the document body. Use this prop to specify a different container for the sortable clone to be appended to. Accepts an HTMLElement or a function returning an HTMLElement that will be invoked before right before sorting begins
disableAutoscrollBooleanfalseDisables autoscrolling while dragging

* OffsetValue can either be a finite Number or a String made up of a number and a unit (px or %). Examples: 10 (which is the same as "10px"), "50%"

SortableElement HOC

PropertyTypeDefaultRequired?Description
indexNumberThis is the element's sortableIndex within it's collection. This prop is required.
collectionNumber or String0The collection the element is part of. This is useful if you have multiple groups of sortable elements within the same SortableContainer. Example
disabledBooleanfalseWhether the element should be sortable or not

FAQ

Running Examples

In root folder, run the following commands to launch React Storybook:

$ npm install
$ npm start

Accessibility

React Sortable HOC supports keyboard sorting out of the box. To enable it, make sure your SortableElement or SortableHandle is focusable. This can be done by setting tabIndex={0} on the outermost HTML node rendered by the component you're enhancing with SortableElement or SortableHandle.

Once an item is focused/tabbed to, pressing SPACE picks it up, ArrowUp or ArrowLeft moves it one place backward in the list, ArrowDown or ArrowRight moves items one place forward in the list, pressing SPACE again drops the item in its new position. Pressing ESC before the item is dropped will cancel the sort operations.

Grid support

Need to sort items in a grid? We've got you covered! Just set the axis prop to xy. Grid support is currently limited to a setup where all the cells in the grid have the same width and height, though we're working hard to get variable width support in the near future.

Item disappearing when sorting / CSS issues

Upon sorting, react-sortable-hoc creates a clone of the element you are sorting (the sortable-helper) and appends it to the end of the <body> tag. The original element will still be in-place to preserve its position in the DOM until the end of the drag (with inline-styling to make it invisible). If the sortable-helper gets messed up from a CSS standpoint, consider that maybe your selectors to the draggable item are dependent on a parent element which isn't present anymore (again, since the sortable-helper is at the end of the <body>). This can also be a z-index issue, for example, when using react-sortable-hoc within a Bootstrap modal, you'll need to increase the z-index of the SortableHelper so it is displayed on top of the modal (see #87 for more details).

Click events being swallowed

By default, react-sortable-hoc is triggered immediately on mousedown. If you'd like to prevent this behaviour, there are a number of strategies readily available. You can use the distance prop to set a minimum distance (in pixels) to be dragged before sorting is enabled. You can also use the pressDelay prop to add a delay before sorting is enabled. Alternatively, you can also use the SortableHandle HOC.

Wrapper props not passed down to wrapped Component

All props for SortableContainer and SortableElement listed above are intentionally consumed by the wrapper component and are not passed down to the wrapped component. To make them available pass down the desired prop again with a different name. E.g.:

const SortableItem = SortableElement(({value, sortIndex}) => (
  <li>
    {value} - #{sortIndex}
  </li>
));

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

Dependencies

React Sortable HOC only depends on invariant. It has the following peerDependencies: react, react-dom

Reporting Issues

If believe you've found an issue, please report it along with any relevant details to reproduce it. The easiest way to do so is to fork the react-sortable-hoc basic setup sandbox on CodeSandbox:

Edit on CodeSandbox

Asking for help

Please do not use the issue tracker for personal support requests. Instead, use Gitter or StackOverflow.

Contributions

Yes please! Feature requests / pull requests are welcome.