A set of higher-order components to turn any list into an animated, touch-friendly, sortable list.
Examples available here: http://clauderic.github.io/react-sortable-hoc/
- Higher Order Components – Integrates with your existing components
- Drag handle, auto-scrolling, locked axis, events, and more!
- Suuuper smooth animations – Chasing the 120FPS (iPad Pro) dream 🌈
- Works with virtualization libraries: react-virtualized, react-tiny-virtual-list, react-infinite, etc.
- Horizontal lists, vertical lists, or a grid ↔ ↕ ⤡
- Touch support 👌
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/umd/react-sortable-hoc.js"></script>
import React, {Component} from 'react';
import {render} from 'react-dom';
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>
);
});
class SortableComponent extends Component {
state = {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
};
onSortEnd = ({oldIndex, newIndex}) => {
this.setState({
items: arrayMove(this.state.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.
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.
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 | |
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 |
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. |
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 get's 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 or option . |
onSortStart | Function | Callback that get's invoked when sorting begins. function({node, index, collection}, event) |
|
onSortMove | Function | Callback that get's invoked during sorting as the cursor moves. function(event) |
|
onSortEnd | Function | Callback that get's invoked when sorting ends. function({oldIndex, newIndex, collection}, e) |
|
useDragHandle | Boolean | false |
If you're using the SortableHandle HOC, set this to true |
lockToContainerEdges | Boolean | false |
You can lock movement of the sortable element to it's parent SortableContainer |
lockOffset | OffsetValue * \ |
[OffsetValue *, OffsetValue *] |
"50%" |
getHelperDimensions | Function | Function | Optional function({node, index, collection}) that should return the computed dimensions of the SortableHelper. See default implementation for more details |
* 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%"
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 |
In root folder:
$ npm install
$ npm run storybook
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.
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).
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.
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>
);
});
React Sortable List has very few dependencies. It depends on invariant
and a handful of lodash
helpers. It has the following peerDependencies: react
, react-dom
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 this jsfiddle.
Please do not use the issue tracker for personal support requests. Instead, use Gitter or StackOverflow.
Yes please! Feature requests / pull requests are welcome.