UNPKG

24.8 kBMarkdownView Raw
1# React Sortable (HOC)
2
3> A set of higher-order components to turn any list into an animated, touch-friendly, sortable list.
4
5[![npm version](https://img.shields.io/npm/v/react-sortable-hoc.svg)](https://www.npmjs.com/package/react-sortable-hoc)
6[![npm downloads](https://img.shields.io/npm/dm/react-sortable-hoc.svg)](https://www.npmjs.com/package/react-sortable-hoc)
7[![license](https://img.shields.io/github/license/mashape/apistatus.svg?maxAge=2592000)](https://github.com/clauderic/react-sortable-hoc/blob/master/LICENSE)
8[![Gitter](https://badges.gitter.im/clauderic/react-sortable-hoc.svg)](https://gitter.im/clauderic/react-sortable-hoc)
9![gzip size](http://img.badgesize.io/https://npmcdn.com/react-sortable-hoc/dist/react-sortable-hoc.umd.min.js?compression=gzip)
10
11### Examples available here: <a href="#">http://clauderic.github.io/react-sortable-hoc/</a>
12
13## Features
14
15- **Higher Order Components** โ€“ Integrates with your existing components
16- **Drag handle, auto-scrolling, locked axis, events, and more!**
17- **Suuuper smooth animations** โ€“ Chasing the 60FPS dream ๐ŸŒˆ
18- **Works with virtualization libraries: [react-virtualized](https://github.com/bvaughn/react-virtualized/), [react-tiny-virtual-list](https://github.com/clauderic/react-tiny-virtual-list), [react-infinite](https://github.com/seatgeek/react-infinite), etc.**
19- **Horizontal lists, vertical lists, or a grid** โ†” โ†• โคก
20- **Touch support** ๐Ÿ‘Œ
21
22## Installation
23
24Using [npm](https://www.npmjs.com/package/react-sortable-hoc):
25
26 $ npm install react-sortable-hoc --save
27
28Then, using a module bundler that supports either CommonJS or ES2015 modules, such as [webpack](https://github.com/webpack/webpack):
29
30```js
31// Using an ES6 transpiler like Babel
32import {SortableContainer, SortableElement} from 'react-sortable-hoc';
33
34// Not using an ES6 transpiler
35var Sortable = require('react-sortable-hoc');
36var SortableContainer = Sortable.SortableContainer;
37var SortableElement = Sortable.SortableElement;
38```
39
40Alternatively, an UMD build is also available:
41
42```html
43<script src="react-sortable-hoc/dist/umd/react-sortable-hoc.js"></script>
44```
45
46## Usage
47
48### Basic Example
49
50```js
51import React, {Component} from 'react';
52import {render} from 'react-dom';
53import {
54 SortableContainer,
55 SortableElement,
56 arrayMove,
57} from 'react-sortable-hoc';
58
59const SortableItem = SortableElement(({value}) => <li>{value}</li>);
60
61const SortableList = SortableContainer(({items}) => {
62 return (
63 <ul>
64 {items.map((value, index) => (
65 <SortableItem key={`item-${index}`} index={index} value={value} />
66 ))}
67 </ul>
68 );
69});
70
71class SortableComponent extends Component {
72 state = {
73 items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
74 };
75 onSortEnd = ({oldIndex, newIndex}) => {
76 this.setState(({items}) => ({
77 items: arrayMove(items, oldIndex, newIndex),
78 }));
79 };
80 render() {
81 return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
82 }
83}
84
85render(<SortableComponent />, document.getElementById('root'));
86```
87
88That's it! React Sortable does not come with any styles by default, since it's meant to enhance your existing components.
89
90More code examples are available [here](https://github.com/clauderic/react-sortable-hoc/blob/master/examples/).
91
92## Why should I use this?
93
94There are already a number of great Drag & Drop libraries out there (for instance, [react-dnd](https://github.com/gaearon/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.
95
96### Prop Types
97
98#### SortableContainer HOC
99
100| Property | Type | Default | Description |
101| :------------------------- | :---------------------------------------------------- | :------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
102| axis | String | `y` | Items can be sorted horizontally, vertically or in a grid. Possible values: `x`, `y` or `xy` |
103| 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`. |
104| helperClass | String | | You can provide a class you'd like to add to the sortable helper to add some styles to it |
105| transitionDuration | Number | `300` | The duration of the transition when elements shift positions. Set this to `0` if you'd like to disable transitions |
106| 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. |
107| pressThreshold | Number | `5` | Number of pixels of movement to tolerate before ignoring a press event. |
108| 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. |
109| shouldCancelStart | Function | [Function](https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableContainer/index.js#L48) | 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` or `option`. |
110| 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}, event)` |
111| onSortStart | Function | | Callback that is invoked when sorting begins. `function({node, index, collection}, event)` |
112| onSortMove | Function | | Callback that is invoked during sorting as the cursor moves. `function(event)` |
113| onSortOver | Function | | Callback that is invoked when moving over an item. `function({index, oldIndex, newIndex, collection}, e)` |
114| onSortEnd | Function | | Callback that is invoked when sorting ends. `function({oldIndex, newIndex, collection}, e)` |
115| useDragHandle | Boolean | `false` | If you're using the `SortableHandle` HOC, set this to `true` |
116| useWindowAsScrollContainer | Boolean | `false` | If you want, you can set the `window` as the scrolling container |
117| 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. |
118| lockToContainerEdges | Boolean | `false` | You can lock movement of the sortable element to it's parent `SortableContainer` |
119| lockOffset | `OffsetValue`\* \| [`OffsetValue`\*, `OffsetValue`\*] | `"50%"` | When `lockToContainerEdges` is set to `true`, this controls the offset distance between the sortable helper and the top/bottom edges of it's parent `SortableContainer`. 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 an `array` (For example: `["0%", "100%"]`). |
120| 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. |
121| getHelperDimensions | Function | [Function](https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableContainer/index.js#L74-L77) | Optional `function({node, index, collection})` that should return the computed dimensions of the SortableHelper. See [default implementation](https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableContainer/index.js#L74-L77) for more details |
122| 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 |
123| disableAutoscroll | Boolean | `false` | Disables autoscrolling while dragging |
124
125\* `OffsetValue` can either be a finite `Number` or a `String` made up of a number and a unit (`px` or `%`).
126Examples: `10` (which is the same as `"10px"`), `"50%"`
127
128#### SortableElement HOC
129
130| Property | Type | Default | Required? | Description |
131| :--------- | :--------------- | :------ | :-------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
132| index | Number | | โœ“ | This is the element's sortableIndex within it's collection. This prop is required. |
133| 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](http://clauderic.github.io/react-sortable-hoc/#/basic-configuration/multiple-lists) |
134| disabled | Boolean | `false` | | Whether the element should be sortable or not |
135
136## FAQ
137
138### Running Examples
139
140In root folder, run the following commands to launch React Storybook:
141
142```
143$ npm install
144$ npm start
145```
146
147### Grid support
148
149Need 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.
150
151### Item disappearing when sorting / CSS issues
152
153Upon 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](https://github.com/clauderic/react-sortable-hoc/issues/87) for more details).
154
155### Click events being swallowed
156
157By 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](https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableHandle/index.js) HOC.
158
159### Wrapper props not passed down to wrapped Component
160
161All 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.:
162
163```js
164const SortableItem = SortableElement(({value, sortIndex}) => (
165 <li>
166 {value} - #{sortIndex}
167 </li>
168));
169
170const SortableList = SortableContainer(({items}) => {
171 return (
172 <ul>
173 {items.map((value, index) => (
174 <SortableItem
175 key={`item-${index}`}
176 index={index}
177 sortIndex={index}
178 value={value}
179 />
180 ))}
181 </ul>
182 );
183});
184```
185
186## Dependencies
187
188React Sortable HOC only depends on [invariant](https://github.com/zertosh/invariant). It has the following peerDependencies: `react`, `react-dom`
189
190## Reporting Issues
191
192If believe you've found an issue, please [report it](https://github.com/clauderic/react-sortable-hoc/issues) along with any relevant details to reproduce it. The easiest way to do so is to fork this [jsfiddle](https://jsfiddle.net/clauderic/6r7r2cva/).
193
194## Asking for help
195
196Please do not use the issue tracker for personal support requests. Instead, use [Gitter](https://gitter.im/clauderic/react-sortable-hoc) or StackOverflow.
197
198## Contributions
199
200Yes please! Feature requests / pull requests are welcome.