react-sortable-hoc README

The project's README from github.com/clauderic/react-sortable-hoc. As one markdown file: README.md.

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 from react-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.

Visit @dnd-kit github repository

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

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

react-sortable-hoc (clauderic/react-sortable-hoc)

Searching Database…

Что это?Набор компонентов высшего порядка (HOC) для React, которые превращают любой список в анимированный, доступный и удобный для сенсорных экранов сортируемый список — горизонтальный, вертикальный или в виде сетки.
Это готовый компонент сортировки или обёртка над моими существующими компонентами?Это библиотека, а не готовый виджет: вы оборачиваете свои уже имеющиеся компоненты списка в HOC, и стилей своих она не приносит — она задумана как улучшение того, что у вас уже есть.
Как добавить её в свой проект?Установите через npm install react-sortable-hoc --save и импортируйте через сборщик, который понимает CommonJS или ES2015-модули, например webpack; также доступна отдельная UMD-сборка.
Безопасно ли до сих пор строить проект на этой библиотеке?Разработка прекращена: она получает только критические обновления безопасности и полагается на findDOMNode, который будущие версии React уберут — когда это произойдёт, библиотека сломается.
Где она работает — в браузерах на компьютере, на телефонах, и там и там?Она работает в браузере везде, где работает React. Поддержка сенсорного ввода работает из коробки, а в README её называют предельно простым и дружелюбным к мобильным устройствам способом сделать списки сортируемыми.
Могут ли пользователи менять порядок элементов с клавиатуры?Да — сортировка с клавиатуры является встроенной функцией доступности, с настраиваемыми кодами клавиш: пробел поднимает и опускает элемент, Escape отменяет, стрелки перемещают элемент.
Работает ли она со списками с виртуализацией, например react-virtualized?Да, она работает с библиотеками виртуализации, включая react-virtualized, react-tiny-virtual-list и react-infinite.
Почему стоит использовать её вместо HTML5 Drag & Drop API или react-dnd?Автор говорит, что большинство библиотек перетаскивания опираются на HTML5 Drag & Drop API, который плохо справляется с сенсорными устройствами, фиксированными осями и анимированной сортировкой; react-sortable-hoc была создана, чтобы закрыть эти пробелы.
Я начинаю новый проект — что рекомендует автор?@dnd-kit — преемник от того же автора: паритет функций, современная и расширяемая архитектура, поддержка сложных сценариев и встроенная доступность. Новым пользователям настоятельно рекомендуется переходить на неё.
Creator
clauderic
Size
21.8 MB
Stars
10.9K
Updated
CommitMay 26
Age
10y
Commits · 90 Days