ubcent / react-sortable

A sortable list component built with React

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React Sortable

A React higher-order component for creating sortable interfaces utilizing the HTML5 drag & drop API.

Mainly tested in latest stable Webkit, Firefox and IE releases.

Check out http://webcloud.se/react-sortable or the index.html file of this repository for an example implementation.

##Installation

npm i react-sortable --save

Example implementation

Here's a sample implementation using the react-sortable higher order component.

import React from 'react';
import { Sortable } from 'react-sortable';

var ListItem = React.createClass({
  displayName: 'SortableListItem',
  render: function() {
    return (
        <div {...this.props} className="list-item">{this.props.item}</div>
    )
  }
})

var SortableListItem = Sortable(ListItem);

var SortableList = React.createClass({

  getInitialState: function() {
    return {
      draggingIndex: null,
      data: this.props.data
    };
  },

  updateState: function(obj) {
    this.setState(obj);
  },

  render: function() {
    var listItems = this.state.data.items.map(function(item, i) {
      return (
          <SortableListItem
              key={i}
              updateState={this.updateState}
              items={this.state.data.items}
              draggingIndex={this.state.draggingIndex}
              sortId={i}
              outline="list"
              item={item}/>
      );
    }, this);

    return (
          <div className="list">{listItems}</div>
    )
  }
});

Here's some example data and a render call to the above component

import ReactDOM from 'react-dom';

var data = {
  items: [
    "Gold",
    "Crimson",
    "Hotpink",
    "Blueviolet",
    "Cornflowerblue"
  ]
};

ReactDOM.render(
    <SortableList data={data} />,
    document.body
);

How it works

The Sortable higher order component will automatically attach the necessary drag event handlers.

It will expects the following properties to be defined on your Item components:

  • key (React recommends that you use this)
  • updateState (the method that will be called when an item is moved)
  • draggingIndex (index of item being dragged)
  • items (data being sorted)
  • outline (list or grid)
  • sortId (index of item)
  • item (the item itself)

Differentces from react-dnd sortable

  • fewer lines of code = easier to implement and modify
  • can handle both horizontal and vertical dragging
  • there is a plan for touch support
  • code is well documented and covered with unit tests
  • but, if you want to have multiple different types of Drag & Drop interactions (not only sortable), you should definately check out react-dnd

Development

Look at README.md in demo folder.

About

A sortable list component built with React

License:MIT License


Languages

Language:JavaScript 93.0%Language:CSS 4.5%Language:HTML 2.5%