react-sortable-hoc
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️
Top Related Projects
Beautiful and accessible drag and drop for lists with React
Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.
React bindings for SortableJS
Drag and Drop for React
Drag-and-drop sortable component for nested data and hierarchies
🖱 A resizable and draggable component for React.
Quick Overview
React Sortable HOC is a set of higher-order components to turn any list into an animated, accessible, and touch-friendly sortable list. It leverages React's component model to provide a flexible and extensible way to add drag-and-drop sorting functionality to your applications.
Pros
- Easy integration with existing React components
- Supports both horizontal and vertical sorting
- Highly customizable with many configuration options
- Excellent performance, even with large lists
Cons
- Learning curve for complex implementations
- Limited built-in styling options
- Occasional issues with nested sortable elements
- Dependency on React may limit use in other frameworks
Code Examples
- Basic sortable list:
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-${value}`} index={index} value={value} />
))}
</ul>
);
});
const MyList = () => {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);
const onSortEnd = ({oldIndex, newIndex}) => {
setItems(arrayMove(items, oldIndex, newIndex));
};
return <SortableList items={items} onSortEnd={onSortEnd} />;
};
- Customizing drag handle:
import { SortableHandle } from 'react-sortable-hoc';
const DragHandle = SortableHandle(() => <span>::</span>);
const SortableItem = SortableElement(({value}) => (
<li>
<DragHandle />
{value}
</li>
));
- Adding animation:
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
const AnimatedSortableList = SortableContainer(({items}) => {
return (
<TransitionGroup component="ul">
{items.map((value, index) => (
<CSSTransition key={value} timeout={300} classNames="fade">
<SortableItem index={index} value={value} />
</CSSTransition>
))}
</TransitionGroup>
);
});
Getting Started
-
Install the package:
npm install react-sortable-hoc
-
Import the necessary components:
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
-
Create your sortable components:
const SortableItem = SortableElement(({value}) => <li>{value}</li>); const SortableList = SortableContainer(({items}) => ( <ul> {items.map((value, index) => ( <SortableItem key={`item-${value}`} index={index} value={value} /> ))} </ul> ));
-
Implement the sorting logic in your component:
const MyComponent = () => { const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']); const onSortEnd = ({oldIndex, newIndex}) => { setItems(arrayMove(items, oldIndex, newIndex)); }; return <SortableList items={items} onSortEnd={onSortEnd} />; };
Competitor Comparisons
Beautiful and accessible drag and drop for lists with React
Pros of react-beautiful-dnd
- Provides a more natural and fluid drag-and-drop experience with animations
- Offers better accessibility features, including keyboard navigation
- Has extensive documentation and examples for various use cases
Cons of react-beautiful-dnd
- Limited to vertical lists and horizontal lists, lacking support for grid layouts
- Has a steeper learning curve due to its specific concepts and terminology
- Performance may degrade with large lists or complex drag operations
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-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>
);
});
<SortableList items={items} onSortEnd={onSortEnd} />
Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.
Pros of Sortable
- Framework-agnostic, can be used with any JavaScript project
- Supports more features out-of-the-box, like multi-drag and swap
- Smaller bundle size, potentially better performance
Cons of Sortable
- Requires more manual setup for React integration
- Less React-specific optimizations and patterns
- May have a steeper learning curve for React developers
Code Comparison
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>
);
});
Sortable:
import Sortable from 'sortablejs';
const el = document.getElementById('items');
const sortable = Sortable.create(el, {
animation: 150,
ghostClass: 'blue-background-class'
});
The code comparison shows that react-sortable-hoc provides a more React-centric approach with higher-order components, while Sortable requires direct DOM manipulation, which may be less ideal in a React environment but offers more flexibility across different frameworks.
React bindings for SortableJS
Pros of react-sortablejs
- Built on top of Sortable.js, a mature and feature-rich library
- Supports more advanced features like multi-list sorting and nested sortables
- Better touch device support and smoother animations
Cons of react-sortablejs
- Slightly larger bundle size due to Sortable.js dependency
- Less React-specific optimizations compared to react-sortable-hoc
- May require more configuration for complex use cases
Code Comparison
react-sortablejs:
import { ReactSortable } from "react-sortablejs";
<ReactSortable list={items} setList={setItems}>
{items.map(item => <div key={item.id}>{item.name}</div>)}
</ReactSortable>
react-sortable-hoc:
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
));
Both libraries offer drag-and-drop functionality for React applications, but react-sortablejs provides a more straightforward API and additional features, while react-sortable-hoc offers a more React-centric approach with potentially better performance for simpler use cases.
Drag and Drop for React
Pros of react-dnd
- More flexible and customizable for complex drag and drop scenarios
- Supports a wider range of drag and drop interactions beyond just sorting
- Provides a lower-level API for fine-grained control over drag and drop behavior
Cons of react-dnd
- Steeper learning curve and more complex implementation
- Requires more boilerplate code for basic sorting functionality
- May be overkill for simple list reordering tasks
Code Comparison
react-dnd:
import { useDrag, useDrop } from 'react-dnd';
const [{ isDragging }, drag] = useDrag({
type: 'ITEM',
item: { id, index },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
react-sortable-hoc:
import { SortableElement, SortableContainer } from 'react-sortable-hoc';
const SortableItem = SortableElement(({ value }) => <li>{value}</li>);
const SortableList = SortableContainer(({ items }) => (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
));
react-dnd offers more flexibility but requires more setup, while react-sortable-hoc provides a simpler API for basic sorting functionality. Choose based on your project's complexity and requirements.
Drag-and-drop sortable component for nested data and hierarchies
Pros of react-sortable-tree
- Specialized for tree structures, offering built-in support for nested hierarchies
- Includes features like node expansion/collapse and custom node rendering
- Provides more tree-specific functionality out of the box
Cons of react-sortable-tree
- Less flexible for non-tree sorting scenarios
- May have a steeper learning curve due to its specialized nature
- Potentially heavier bundle size due to additional tree-specific features
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 }) => (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
));
react-sortable-tree is more suited for complex tree structures, while react-sortable-hoc offers greater flexibility for various sorting scenarios. The code comparison shows that react-sortable-tree provides a more straightforward API for tree structures, whereas react-sortable-hoc requires more setup but allows for custom list implementations.
🖱 A resizable and draggable component for React.
Pros of react-rnd
- Offers both resizing and dragging functionality, providing more versatile component manipulation
- Supports custom handles for resizing, allowing for greater UI customization
- Provides a simpler API for basic resizing and dragging operations
Cons of react-rnd
- Less focused on sorting and reordering, which is the primary strength of react-sortable-hoc
- May have a steeper learning curve for complex sorting scenarios
- Lacks some advanced features specific to sorting, such as auto-scrolling and lock axis
Code Comparison
react-rnd:
<Rnd
default={{
x: 0,
y: 0,
width: 320,
height: 200
}}
>
Resizable and draggable component
</Rnd>
react-sortable-hoc:
const SortableList = SortableContainer(({items}) => (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
));
Both libraries offer powerful functionality for manipulating React components, but they focus on different aspects. react-rnd excels in providing a straightforward way to create resizable and draggable elements, while react-sortable-hoc specializes in creating sortable lists and grids with advanced sorting features.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Warning
This library is no longer actively maintained. It will continue to receive critical security updates, but there are no new features planned. In future versions of React, the
findDOMNode
method will be deprecated. This method is a critical piece of the architecture ofÂreact-sortable-hoc
, and the library will stop working in the future when that method is removed fromreact-dom
.All development efforts have been redirected towards @dnd-kit. It provides feature parity, built with a modern and extensible architecture, supports complex use-cases and has accessibility features built-in. New consumers are strongly encouraged to adopt @dnd-kit instead of adopting
react-sortable-hoc
.
A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list
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
Property | Type | Default | Description |
---|---|---|---|
axis | String | y | Items can be sorted horizontally, vertically or in a grid. Possible values: x , y or xy |
lockAxis | String | If 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 . | |
helperClass | String | You can provide a class you'd like to add to the sortable helper to add some styles to it | |
transitionDuration | Number | 300 | The duration of the transition when elements shift positions. Set this to 0 if you'd like to disable transitions |
keyboardSortingTransitionDuration | Number | transitionDuration | The 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 |
keyCodes | Array | { lift: [32], drop: [32], cancel: [27], up: [38, 37], down: [40, 39] } | An object containing an array of keycodes for each keyboard-accessible action. |
pressDelay | Number | 0 | If 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. |
pressThreshold | Number | 5 | Number of pixels of movement to tolerate before ignoring a press event. |
distance | Number | 0 | If 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. |
shouldCancelStart | Function | Function | This 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 . |
updateBeforeSortStart | Function | This 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) | |
onSortStart | Function | Callback that is invoked when sorting begins. function({node, index, collection, isKeySorting}, event) | |
onSortMove | Function | Callback that is invoked during sorting as the cursor moves. function(event) | |
onSortOver | Function | Callback that is invoked when moving over an item. function({index, oldIndex, newIndex, collection, isKeySorting}, e) | |
onSortEnd | Function | Callback that is invoked when sorting ends. function({oldIndex, newIndex, collection, isKeySorting}, e) | |
useDragHandle | Boolean | false | If you're using the SortableHandle HOC, set this to true |
useWindowAsScrollContainer | Boolean | false | If you want, you can set the window as the scrolling container |
hideSortableGhost | Boolean | true | Whether 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. |
lockToContainerEdges | Boolean | false | You can lock movement of the sortable element to it's parent SortableContainer |
lockOffset | OffsetValue * | [OffsetValue *, OffsetValue *] | "50%" | WhenlockToContainerEdges is 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%"] ). |
getContainer | Function | Optional 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. | |
getHelperDimensions | Function | Function | Optional function({node, index, collection}) that should return the computed dimensions of the SortableHelper. See default implementation for more details |
helperContainer | HTMLElement | Function | document.body | By 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 |
disableAutoscroll | Boolean | false | Disables 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
Property | Type | Default | Required? | Description |
---|---|---|---|---|
index | Number | â | This is the element's sortableIndex within it's collection. This prop is required. | |
collection | Number or String | 0 | The collection the element is part of. This is useful if you have multiple groups of sortable elements within the same SortableContainer . Example | |
disabled | Boolean | false | Whether 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:
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.
Top Related Projects
Beautiful and accessible drag and drop for lists with React
Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.
React bindings for SortableJS
Drag and Drop for React
Drag-and-drop sortable component for nested data and hierarchies
🖱 A resizable and draggable component for React.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot