Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-sortable-hoc

clauderic1.5mMIT2.0.0TypeScript support: included

Set of higher-order components to turn any list into a sortable, touch-friendly, animated list

react, reactjs, react-component, sortable, sortable-list, list, sortable list, smooth, animated, hoc, higher-order, component

readme

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

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<Number> {
  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%" 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%"]).
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:

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.

changelog

Change Log

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

2.0.0 (2021-03-18)

Bug Fixes

  • Fixed React strict mode warnings by upgrading to new React context API and removing legacy refs (#624). Since the new context API was introduced in React ^16.3.0, the peer dependencies had to be upgraded accordingly.
  • Check if event is cancellable before calling event.preventDefault() #752.
  • Fix touch events being lost by listening to event.target on mobile #586.
  • Added disableAutoscroll prop to PropType definitions #755.

Dependencies

  • Updated minimum peer dependencies for react and react-dom to ^16.3.0. Added ^17.0.0 to list of supported peer dependencies.

1.11.0 (2020-01-20)

Bug Fixes

Features

1.10.1 (2019-08-22)

Bug Fixes

  • PropType definition for keyCodes was incorrect (eaf5070)

1.10.0 (2019-08-22)

Bug Fixes

Features

  • Add keyCodes prop to configure the keyboard shortcuts (#588) (4c6d8dd)

1.9.1 (2019-04-24)

Bug Fixes

  • do not copy canvas context if it has neither width nor height (#530) (3808437)
  • pass isKeySorting to onSortOver and updateBeforeSortStart handler props (#531) (763fd33

1.9.0 (2019-04-23)

Bug Fixes

  • issue with radio input name collision when cloning helper (5337c97)

Features

  • add support for keyboard sorting (#501) (439b92f)
  • prevent sort start on contentEditable target (d64c8cf)

1.8.3 (2019-03-20)

Bug Fixes

  • issue with windowAsScrollContainer and translation offsets (0391e62)

Features

  • Add disableAutoscroll prop (#484) (7845e76)
  • added helperContainer prop (286eff4)
  • allow helperContainer prop to be a function returning an HTMLElement (#489) (f4a9b4a)
  • Detect scroll container automatically (#507) (6572921)

1.8.2 (2019-03-19)

Bug Fixes

  • issue with getComputedStyle and getScrollingParent (b104249)

1.8.1 (2019-03-18)

Bug Fixes

  • issue with cloning canvas context of dragged items (#512) (4df34ad)

1.8.0 (2019-03-18)

Bug Fixes

  • added prop-types to peerDependencies (0e855c5)
  • copy canvas content into cloned node (43ad122)
  • get updated index after updateBeforeSortStart (4471a0a)
  • helperContainer PropType definition broke server-side rendering (#471) (c0eef97)
  • lock axis story should not use lockToContainerEdges (db1d3a9)
  • omit disableAutoscroll prop (#502) (e994e73)
  • omit spreading helperContainer prop (#497) (12bafdf)
  • overflow bug while dragging an item upwards in a grid (1a2c87e)
  • replace process.env.NODE_ENV in UMD builds (16135df)
  • update helperContainer prop type definition (#491) (fd30383)
  • updated the behaviour of disabled elements (bd3d041)
  • virtualized collection grid bug (a57975c)

Features

  • Add disableAutoscroll prop (#484) (7845e76)
  • added helperContainer prop (286eff4)
  • allow helperContainer prop to be a function returning an HTMLElement (#489) (f4a9b4a)
  • Detect scroll container automatically (#507) (6572921)

1.7.1 (2019-03-06)

Bug Fixes

  • updated the behaviour of disabled elements (bd3d041)

1.7.0 (2019-03-06)

Bug Fixes

  • updated the behaviour of disabled elements (bd3d041)

1.6.1 (2019-02-11)

Bug Fixes

1.6.0 (2019-02-07)

Features

1.5.4 (2019-02-07)

Bug Fixes

  • overflow bug while dragging an item upwards in a grid (1a2c87e)
  • virtualized collection grid bug (a57975c)

1.5.3 (2019-01-25)

Bug Fixes

  • omit spreading helperContainer prop on WrappedComponent (#497) (12bafdf)

1.5.2 (2019-01-22)

Bug Fixes

  • invalid helperContainer PropType definition (#493) (dc1d18f)

1.5.1 (2019-01-22)

Bug Fixes

  • update helperContainer prop type definition (#491) (fd30383)

1.5.0 (2019-01-22)

Features

  • allow helperContainer prop to be a function returning an HTMLElement (f4a9b4a)

1.4.0 (2019-01-10)

Bug Fixes

  • Fix CommonJS and UMD builds by using Rollup and Babel to generate the bundles (#474)

1.3.0 (2019-01-08)

Bug Fixes

  • helperContainer PropType definition broke server-side rendering (#471) (c0eef97)

1.2.0 (2019-01-08)

Features

  • added helperContainer prop (286eff4)

1.1.0 (2019-01-07)

Features

  • added updateBeforeSortStart prop (162857b)

1.0.0 (2019-01-07)

BREAKING CHANGES

  • The UMD release no longer includes babel-polyfill, you will need to include your own polyfills in order to support older browsers.

0.8.4

  • Fix a bug when you use SortableHandle and distance prop #447

0.8.3

  • Fix: TouchEvent is undefined in certain browsers, such as Safari #382

0.8.1

  • Fix scrolling issues on mobile with anchor tag elements #380
  • Update TypeScript type definition for ContainerGetter to accept Promises that return HTMLElements

0.8.0

  • Allow getContainer to return a promise. This is useful when the container node is rendered by a parent component, since componentDidMount fires backwards (from child to parent) #155

0.7.4

  • Fix typo in getLockPixelOffset helper

0.7.3

  • Fix issues with distance and pressThreshold props on mobile #378

0.7.2

  • Fix issues with TypeScript type definitions

0.7.1

  • Provide TypeScript type definitions out of the box #377
  • Fix potential issues with calling removeEventListeners on componentWillUnmount if the container node has already unmounted #376

0.7.0

  • [Breaking change] Removed lodash dependency. For users wishing to support Internet Explorer, a polyfill for Array.prototype.find will be required
  • Added onSortOver prop that gets invoked when sorting over an element #278
  • Fix useWindowAsScrollContainer #306

0.6.8

Update react and react-dom peerdependency requirements for React 16+ #283. Thanks @jnsdls!

0.6.7

Fixes issues with Jest Snapshot testing trying to serialize the window object and running out of memory #249. Thanks @cameronmcefee!

0.6.6

Fixes an issue with Internet Explorer 11 introduced in 0.6.5 #248. Thanks @humiston!

0.6.5

Fixes the position of the sortable helper when the page is scrolled #213

0.6.4

Fix: when cloning the element that is being sorted, we no longer update the value of cloned file inputs #232

0.6.3

Fixes issues caused by a disabled SortableElement being moved when distance is set to a value other than 0

0.6.2

Use prop-types package for PropType validation for compatibility with React ^15.5

0.6.1

Tweak: default to pointerEvents: none on sortable helper, this way the underlying view can still be scrolled using the trackpad/mousewheel while sorting #160

0.6.0

Feature: added pressThreshold prop to make pressDelay fault tolerant #159

0.5.0

Tweak: button elements are now included in the default shouldCancelStart implementation #142. Fix: Omit getHelperDimensions before passing down props in SortableContainer

0.4.12

Fix: This release fixes some issues caused by the onSortEnd callback being invoked before setState #82.

0.4.10

Fix: This version fixes issues with nested SortableContainer elements using drag handles from also dragging their parent #112, #127(https://github.com/clauderic/react-sortable-hoc/pull/127). Thanks @DeadHeadRussell!

0.4.9

Fix: This release fixes a bug introduced in 0.4.8 caused by calling the forEach method directly on a NodeList, which is undefined in a number of browsers #125

0.4.8

Fix: Added logic to ensure that select, input and textarea fields in SortableElement always retain their value when the element is cloned (this happens when sorting begins) #122 #123. Thanks @tomasztomys!

0.4.7

Fix: This release fixes a bug in Firefox caused by active anchor tags preventing mousemove events from being fired #118

0.4.5

Fix: getHelperDimensions height was not being used (Thanks @SMenigat!)

0.4.4

Tweak: cherry-picking lodash methods instead of importing the entire bundle (slipped by in a PR, thanks for pointing this out @arackaf!)

0.4.3

Fixes an edge-case bug in Firefox where window.getComputedStyle() returns null inside an iframe with display: none #106. Thanks @funnel-mark!

0.4.2

Fixes an issue when attempting to sort items while rapidly moving the mouse. By setting an immediate timer, we move the cancel event to the tail of the timer queue, and ensure that it is fired after the pressTimer #80. Thanks @v0lkan!

0.4.0

  • Fix a timing issue in Chrome caused by setTimeout #71
  • Private props are no longer passed down to the wrapped component #98

0.3.0

Added grid support for elements of equal widths / heights #4 #86. Huge shout-out to @richmeij for making this happen!

0.2.0

Add a getHelperDimensions prop to control SortableHelper size #83. Thanks @nervetattoo!

0.1.1

Added touchCancel listener to properly handle canceled touches #73

0.1.0

  • Force box-sizing: border-box on sortable helper #67
  • Support changing an item's collection prop on the fly #66

0.0.11

Utilize babel-plugin-transform-runtime to utilize babelHelpers without them being required in application code #45

0.0.10

The arrayMove helper no longer mutates the array, it now returns a new array #61

0.0.9

Server-side rendering bugfix: safeguard against document being undefined #59

0.0.8

  • Added distance prop (#35)
  • Added a shouldCancelStart (#47, #36, #41) prop to programatically cancel sorting before it begins.
  • Prevent right click from causing sort start (#46)

0.0.7

Fixes server-side rendering (window undefined) (#39)

0.0.6

  • Added support for a custom container (#37)
  • Fix changing disable property while receiving props (#34)