Giter Site home page Giter Site logo

sortablejs / react-sortablejs Goto Github PK

View Code? Open in Web Editor NEW
1.9K 26.0 206.0 6.75 MB

React bindings for SortableJS

Home Page: http://sortablejs.github.io/react-sortablejs/

License: MIT License

JavaScript 0.33% TypeScript 99.67%
react sortable drag-and-drop draggable multidrag

react-sortablejs's Introduction

Sortable   Financial Contributors on Open Collective CircleCI DeepScan grade npm

Sortable is a JavaScript library for reorderable drag-and-drop lists.

Demo: http://sortablejs.github.io/Sortable/

Features

  • Supports touch devices and modern browsers (including IE9)
  • Can drag from one list to another or within the same list
  • CSS animation when moving items
  • Supports drag handles and selectable text (better than voidberg's html5sortable)
  • Smart auto-scrolling
  • Advanced swap detection
  • Smooth animations
  • Multi-drag support
  • Support for CSS transforms
  • Built using native HTML5 drag and drop API
  • Supports
  • Supports any CSS library, e.g. Bootstrap
  • Simple API
  • Support for plugins
  • CDN
  • No jQuery required (but there is support)
  • Typescript definitions at @types/sortablejs

Articles


Getting Started

Install with NPM:

npm install sortablejs --save

Install with Bower:

bower install --save sortablejs

Import into your project:

// Default SortableJS
import Sortable from 'sortablejs';

// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';

// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';

Cherrypick plugins:

// Cherrypick extra plugins
import Sortable, { MultiDrag, Swap } from 'sortablejs';

Sortable.mount(new MultiDrag(), new Swap());


// Cherrypick default plugins
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';

Sortable.mount(new AutoScroll());

Usage

<ul id="items">
	<li>item 1</li>
	<li>item 2</li>
	<li>item 3</li>
</ul>
var el = document.getElementById('items');
var sortable = Sortable.create(el);

You can use any element for the list and its elements, not just ul/li. Here is an example with divs.


Options

var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	delayOnTouchOnly: false, // only delay if user is using touch
	touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
	disabled: false, // Disables the sortable if set to true.
	store: null,  // @see Store
	animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
	easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
	handle: ".my-handle",  // Drag handle selector within list items
	filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
	preventOnFilter: true, // Call `event.preventDefault()` when triggered `filter`
	draggable: ".item",  // Specifies which items inside the element should be draggable

	dataIdAttr: 'data-id', // HTML attribute that is used by the `toArray()` method

	ghostClass: "sortable-ghost",  // Class name for the drop placeholder
	chosenClass: "sortable-chosen",  // Class name for the chosen item
	dragClass: "sortable-drag",  // Class name for the dragging item

	swapThreshold: 1, // Threshold of the swap zone
	invertSwap: false, // Will always use inverted swap zone if set to true
	invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
	direction: 'horizontal', // Direction of Sortable (will be detected automatically if not given)

	forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

	fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
	fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
	fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

	dragoverBubble: false,
	removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
	emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


	setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
		dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
	},

	// Element is chosen
	onChoose: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element is unchosen
	onUnchoose: function(/**Event*/evt) {
		// same properties as onEnd
	},

	// Element dragging started
	onStart: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element dragging ended
	onEnd: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		evt.to;    // target list
		evt.from;  // previous list
		evt.oldIndex;  // element's old index within old parent
		evt.newIndex;  // element's new index within new parent
		evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
		evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
		evt.clone // the clone element
		evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
	},

	// Element is dropped into the list from another list
	onAdd: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Changed sorting within list
	onUpdate: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Called by any change to the list (add / update / remove)
	onSort: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Element is removed from the list into another list
	onRemove: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Attempt to drag a filtered element
	onFilter: function (/**Event*/evt) {
		var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
	},

	// Event when you move an item in the list or between lists
	onMove: function (/**Event*/evt, /**Event*/originalEvent) {
		// Example: https://jsbin.com/nawahef/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // DOMRect {left, top, right, bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // DOMRect
		evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
		originalEvent.clientY; // mouse position
		// return false; — for cancel
		// return -1; — insert before target
		// return 1; — insert after target
		// return true; — keep default insertion point based on the direction
		// return void; — keep default insertion point based on the direction
	},

	// Called when creating a clone of element
	onClone: function (/**Event*/evt) {
		var origEl = evt.item;
		var cloneEl = evt.clone;
	},

	// Called when dragging element changes position
	onChange: function(/**Event*/evt) {
		evt.newIndex // most likely why this event is used is to get the dragging element's current index
		// same properties as onEnd
	}
});

group option

To drag elements from one list into another, both lists must have the same group value. You can also define whether lists can give away, give and keep a copy (clone), and receive elements.

  • name: String — group name
  • pull: true|false|["foo", "bar"]|'clone'|function — ability to move from the list. clone — copy the item, rather than move. Or an array of group names which the elements may be put in. Defaults to true.
  • put: true|false|["baz", "qux"]|function — whether elements can be added from other lists, or an array of group names from which elements can be added.
  • revertClone: boolean — revert cloned element to initial position after moving to a another list.

Demo:


sort option

Allow sorting inside list.

Demo: https://jsbin.com/jayedig/edit?js,output


delay option

Time in milliseconds to define when the sorting should start. Unfortunately, due to browser restrictions, delaying is not possible on IE or Edge with native drag & drop.

Demo: https://jsbin.com/zosiwah/edit?js,output


delayOnTouchOnly option

Whether or not the delay should be applied only if the user is using touch (eg. on a mobile device). No delay will be applied in any other case. Defaults to false.


swapThreshold option

Percentage of the target that the swap zone will take up, as a float between 0 and 1.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertSwap option

Set to true to set the swap zone to the sides of the target, for the effect of sorting "in between" items.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertedSwapThreshold option

Percentage of the target that the inverted swap zone will take up, as a float between 0 and 1. If not given, will default to swapThreshold.

Read more


direction option

Direction that the Sortable should sort in. Can be set to 'vertical', 'horizontal', or a function, which will be called whenever a target is dragged over. Must return 'vertical' or 'horizontal'.

Read more

Example of direction detection for vertical list that includes full column and half column elements:

Sortable.create(el, {
	direction: function(evt, target, dragEl) {
		if (target !== null && target.className.includes('half-column') && dragEl.className.includes('half-column')) {
			return 'horizontal';
		}
		return 'vertical';
	}
});

touchStartThreshold option

This option is similar to fallbackTolerance option.

When the delay option is set, some phones with very sensitive touch displays like the Samsung Galaxy S8 will fire unwanted touchmove events even when your finger is not moving, resulting in the sort not triggering.

This option sets the minimum pointer movement that must occur before the delayed sorting is cancelled.

Values between 3 to 5 are good.


disabled options

Disables the sortable if set to true.

Demo: https://jsbin.com/sewokud/edit?js,output

var sortable = Sortable.create(list);

document.getElementById("switcher").onclick = function () {
	var state = sortable.option("disabled"); // get

	sortable.option("disabled", !state); // set
};

handle option

To make list items draggable, Sortable disables text selection by the user. That's not always desirable. To allow text selection, define a drag handler, which is an area of every list element that allows it to be dragged around.

Demo: https://jsbin.com/numakuh/edit?html,js,output

Sortable.create(el, {
	handle: ".my-handle"
});
<ul>
	<li><span class="my-handle">::</span> list item text one
	<li><span class="my-handle">::</span> list item text two
</ul>
.my-handle {
	cursor: move;
	cursor: -webkit-grabbing;
}

filter option

Sortable.create(list, {
	filter: ".js-remove, .js-edit",
	onFilter: function (evt) {
		var item = evt.item,
			ctrl = evt.target;

		if (Sortable.utils.is(ctrl, ".js-remove")) {  // Click on remove button
			item.parentNode.removeChild(item); // remove sortable item
		}
		else if (Sortable.utils.is(ctrl, ".js-edit")) {  // Click on edit link
			// ...
		}
	}
})

ghostClass option

Class name for the drop placeholder (default sortable-ghost).

Demo: https://jsbin.com/henuyiw/edit?css,js,output

.ghost {
  opacity: 0.4;
}
Sortable.create(list, {
  ghostClass: "ghost"
});

chosenClass option

Class name for the chosen item (default sortable-chosen).

Demo: https://jsbin.com/hoqufox/edit?css,js,output

.chosen {
  color: #fff;
  background-color: #c00;
}
Sortable.create(list, {
  delay: 500,
  chosenClass: "chosen"
});

forceFallback option

If set to true, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser. This gives us the possibility to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.

On top of that, the Fallback always generates a copy of that DOM Element and appends the class fallbackClass defined in the options. This behaviour controls the look of this 'dragged' Element.

Demo: https://jsbin.com/sibiput/edit?html,css,js,output


fallbackTolerance option

Emulates the native drag threshold. Specify in pixels how far the mouse should move before it's considered as a drag. Useful if the items are also clickable like in a list of links.

When the user clicks inside a sortable element, it's not uncommon for your hand to move a little between the time you press and the time you release. Dragging only starts if you move the pointer past a certain tolerance, so that you don't accidentally start dragging every time you click.

3 to 5 are probably good values.


dragoverBubble option

If set to true, the dragover event will bubble to parent sortables. Works on both fallback and native dragover event. By default, it is false, but Sortable will only stop bubbling the event once the element has been inserted into a parent Sortable, or can be inserted into a parent Sortable, but isn't at that specific time (due to animation, etc).

Since 1.8.0, you will probably want to leave this option as false. Before 1.8.0, it may need to be true for nested sortables to work.


removeCloneOnHide option

If set to false, the clone is hidden by having it's CSS display property set to none. By default, this option is true, meaning Sortable will remove the cloned element from the DOM when it is supposed to be hidden.


emptyInsertThreshold option

The distance (in pixels) the mouse must be from an empty sortable while dragging for the drag element to be inserted into that sortable. Defaults to 5. Set to 0 to disable this feature.

Demo: https://jsbin.com/becavoj/edit?js,output

An alternative to this option would be to set a padding on your list when it is empty.

For example:

ul:empty {
  padding-bottom: 20px;
}

Warning: For :empty to work, it must have no node inside (even text one).

Demo: https://jsbin.com/yunakeg/edit?html,css,js,output


Event object (demo)

  • to:HTMLElement — list, in which moved element
  • from:HTMLElement — previous list
  • item:HTMLElement — dragged element
  • clone:HTMLElement
  • oldIndex:Number|undefined — old index within parent
  • newIndex:Number|undefined — new index within parent
  • oldDraggableIndex: Number|undefined — old index within parent, only counting draggable elements
  • newDraggableIndex: Number|undefined — new index within parent, only counting draggable elements
  • pullMode:String|Boolean|undefined — Pull mode if dragging into another sortable ("clone", true, or false), otherwise undefined

move event object

  • to:HTMLElement
  • from:HTMLElement
  • dragged:HTMLElement
  • draggedRect:DOMRect
  • related:HTMLElement — element on which have guided
  • relatedRect:DOMRect
  • willInsertAfter:Booleantrue if will element be inserted after target (or false if before)

Methods

option(name:String[, value:*]):*

Get or set the option.

closest(el:HTMLElement[, selector:String]):HTMLElement|null

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

toArray():String[]

Serializes the sortable's item data-id's (dataIdAttr option) into an array of string.

sort(order:String[], useAnimation:Boolean)

Sorts the elements according to the array.

var order = sortable.toArray();
sortable.sort(order.reverse(), true); // apply
save()

Save the current sorting (see store)

destroy()

Removes the sortable functionality completely.


Store

Saving and restoring of the sort.

<ul>
	<li data-id="1">order</li>
	<li data-id="2">save</li>
	<li data-id="3">restore</li>
</ul>
Sortable.create(el, {
	group: "localStorage-example",
	store: {
		/**
		 * Get the order of elements. Called once during initialization.
		 * @param   {Sortable}  sortable
		 * @returns {Array}
		 */
		get: function (sortable) {
			var order = localStorage.getItem(sortable.options.group.name);
			return order ? order.split('|') : [];
		},

		/**
		 * Save the order of elements. Called onEnd (when the item is dropped).
		 * @param {Sortable}  sortable
		 */
		set: function (sortable) {
			var order = sortable.toArray();
			localStorage.setItem(sortable.options.group.name, order.join('|'));
		}
	}
})

Bootstrap

Demo: https://jsbin.com/visimub/edit?html,js,output

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>


<!-- Latest Sortable -->
<script src="http://SortableJS.github.io/Sortable/Sortable.js"></script>


<!-- Simple List -->
<ul id="simpleList" class="list-group">
	<li class="list-group-item">This is <a href="http://SortableJS.github.io/Sortable/">Sortable</a></li>
	<li class="list-group-item">It works with Bootstrap...</li>
	<li class="list-group-item">...out of the box.</li>
	<li class="list-group-item">It has support for touch devices.</li>
	<li class="list-group-item">Just drag some elements around.</li>
</ul>

<script>
    // Simple list
    Sortable.create(simpleList, { /* options */ });
</script>

Static methods & properties

Sortable.create(el:HTMLElement[, options:Object]):Sortable

Create new instance.


Sortable.active:Sortable

The active Sortable instance.


Sortable.dragged:HTMLElement

The element being dragged.


Sortable.ghost:HTMLElement

The ghost element.


Sortable.clone:HTMLElement

The clone element.


Sortable.get(element:HTMLElement):Sortable

Get the Sortable instance on an element.


Sortable.mount(plugin:...SortablePlugin|SortablePlugin[])

Mounts a plugin to Sortable.


Sortable.utils
  • on(el:HTMLElement, event:String, fn:Function) — attach an event handler function
  • off(el:HTMLElement, event:String, fn:Function) — remove an event handler
  • css(el:HTMLElement):Object — get the values of all the CSS properties
  • css(el:HTMLElement, prop:String):Mixed — get the value of style properties
  • css(el:HTMLElement, prop:String, value:String) — set one CSS properties
  • css(el:HTMLElement, props:Object) — set more CSS properties
  • find(ctx:HTMLElement, tagName:String[, iterator:Function]):Array — get elements by tag name
  • bind(ctx:Mixed, fn:Function):Function — Takes a function and returns a new one that will always have a particular context
  • is(el:HTMLElement, selector:String):Boolean — check the current matched set of elements against a selector
  • closest(el:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Null — for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
  • clone(el:HTMLElement):HTMLElement — create a deep copy of the set of matched elements
  • toggleClass(el:HTMLElement, name:String, state:Boolean) — add or remove one classes from each element
  • detectDirection(el:HTMLElement):String — automatically detect the direction of the element as either 'vertical' or 'horizontal'
  • index(el:HTMLElement, selector:String):Number — index of the element within its parent for a selected set of elements
  • getChild(el:HTMLElement, childNum:Number, options:Object, includeDragEl:Boolean):HTMLElement — get the draggable element at a given index of draggable elements within a Sortable instance
  • expando:String — expando property name for internal use, sortableListElement[expando] returns the Sortable instance of that elemenet

Plugins

Extra Plugins (included in complete versions)

Default Plugins (included in default versions)


CDN

<!-- jsDelivr :: Sortable :: Latest (https://www.jsdelivr.com/package/npm/sortablejs) -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

Contributing (Issue/PR)

Please, read this.


Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

MIT LICENSE

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

react-sortablejs's People

Contributors

andresin87 avatar cangshudada avatar cheton avatar dependabot[bot] avatar dteske25 avatar eljusto avatar ermyril avatar exentrich avatar feketegy avatar herol3oy avatar i-akhmadullin avatar iamjulianacosta avatar jakobsturm avatar kierandotco avatar kjanoudi avatar krnlde avatar leqwasd avatar megawac avatar mohan-bitla avatar msftenhanceprovenance avatar owen-m1 avatar ramen-curator avatar richorama avatar semantic-release-bot avatar shelimov avatar tjramage avatar turnerniles avatar volenarg avatar waynevanson avatar zachiah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-sortablejs's Issues

Name confusion with `react-sortable` npm package

Since there's another project in npm called react-sortable, and this project's name in npm is react-sortablejs, I think it would make sense to rename this GitHub repo and all documentation to always refer to this project as react-sortablejs.

Virtualization

Can this library work with virtualization library, ie. react-virtualized,...

Uncaught Error: Cannot call beginDrag while dragging.

Hi,

I get the following error when dragging li items after the first time.
It looks like drop / end doesn't occur? Has anyone got the issue?

I am using the uncontrolled component example from index.jsx, nested into a react-bootstrap modal.

Many thanks!

Question on Shared Groups

I've got this following bit of code that renders out a board. I placed the Shared group option in and I can't move any item to other lists. Each board is part of another list. Do I have to render the Sortable directly?

  render() {
    let items = this.props.tasks.map((task, index) => <Task key={index} {...task}/>);
    return (
      <Col sm={3} className='board'>
        <div className='board-container'>
          <div className='board-title'>
            {this.props.title}
          </div>
            <div className='board-list-container'>
            <div className='board-list'>
              <Sortable
                options={{
                  group: 'shared'
                }}>
                {items}
              </Sortable>
            </div>
          </div>
        </div>
      </Col>
    );
  }

Edit: I tried this

  render() {
    let items = this.props.tasks.map((task, index) => <Task key={index} {...task}/>);
    return (
      <Sortable
        options={{
          group: 'shared'
        }}>
        {items}
      </Sortable>
    );
  }

It still doesn't work
For each board though I have the following:

render() {
   let boards = Array.from(this.state.boards);
   return (
     <div className='boards'>
       {boards.map(board =>
         <Col sm={3} className='board'>
           <div className='board-container'>
             <div className='board-title'>
               {board[1].title}
             </div>
               <div className='board-list-container'>
               <div className='board-list'>
                 <Board key={board[0]} {...board[1]} /> ///// <---- Each board here
               </div>
             </div>
           </div>
         </Col>
       )}
     </div>
   );
 }

Failed prop type: Invalid prop `tag` of type `function` supplied to `Sortable`, expected `string`

Trying to use this library with Ant design. My implementation is as follows:

import { Row } from "antd"
<Sortable tag={Row} />

This works, but I get the error in the title `Failed prop type: Invalid prop 'tag' of type 'function' supplied to 'Sortable', expected 'string'.

I haven't had a chance to look at this libraries source code yet, but is it possible to relax the prop type for the tag?

I tried using a string of "Row" for the tag but I get even more errors that seem to come more from React's end.

<Row /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.

The tag <Row> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

Way to get props/state of sortable items

Hi!
Have some way to access sortable items props/state?
in code below in onUpdatecallback i want get some props from dragged Todo

class Todos extends Component {
    ...
    renderTodos() {
        return this.state.todos.map(todo => {
            return <Todo {...todo} key={todo.id} />
        })
    }
    render() {
        let opt = {
            onUpdate: this.onUpdate,
            model: 'todos'
        }

        return <div>
            <Sortable tag="div" className="todos-wrapper" options={opt}>
                {this.renderTodos()}
            </Sortable>
        </div>
    }
}

Move and Clone elements from the same list

Hello,

I have 3 List. Client is supposed to drag elements from list A to B and C. Would it be possible to clone elements when user drag from list A to B, BUT move it (remove from A) when user drags from A to C?

I was trying to always clone elements, and remove it manually from list A if needed, but after upgrading to React 15 it throws an error.

Best Regards,

Is there an easy way to access attributes of target element?

I have a custom data attribute on my draggable elements that consist of some extra information. I can access the attributes of the dragged item but I cannot find a way to get attributes of the target element.

onChange={(order, sortable, evt) => {
    console.log(evt.item.attributes.data.value) // works fine
    console.log(evt.target.attributes.data.value) // need something like this
}

How can do this?

React 16 Support

Currently, this project looks for React 14 or 15. Any plans for 16? Would love to use this in my current project. Thanks!

Making component fully controlled (props-driven)

Hello, thank you for this library.

I have stumbled upon a problem, where I need to dynamically toggle Sortable disability through props change. However, Sortable does not respond to change of options of any kind. This is caused due to these lines:

delete props.options;
delete props.onChange;

Is there any particular reason for that?

I was able to achieve my goals by removing above lines and with this:

componentDidUpdate(prevProps, prevState) {
        if (prevProps.options.disabled !== this.props.options.disabled) {
            this.sortable.option('disabled', this.props.options.disabled);
        }
}

It also can be expanded to make component respond for any option change (since RubaXa's API allows that)

I think this component should follow React idioms, and be open to be controlled from outside using props, and it's a responsibility of this component for doing so. I can prepare PR for this change, if it's welcome

Controlled Component Not Deleting Dragged Item

Hi there,

I just tried the example on my local machine and the controlled component does not seem to work. The dragged item gets added back to the original list.

Sortable JS - 1.5.0
React Sortable JS - 1.3.0

Text Select

I am not able to select the text inside the sortable component.
Is there any property through which text selection is possible.

Support server-side rendering

Got this error when rendering on server.

[1] [piping] error given was: ReferenceError: window is not defined
[1]     at node_modules/sortablejs/Sortable.js:57:9

Not update sortable items

Hi!
i have peace of code

class Todos extends Component {
    state = {
        todos: []
    }

    componentWillMount() {
        this.setState({
            todos: this.props.todos
        })
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            todos: nextProps.todos
        })
    }

    renderTodos() {
        return this.state.todos.map(todo => {
            return <Todo {...todo} key={todo.id} />
        })
    }
    render() {
        let opt = {
            onUpdate: this.onUpdate,
            model: 'todos'
        }

        return <div>
            <Sortable tag="div" className="todos-wrapper" options={opt}>
                {this.renderTodos()}
            </Sortable>
        </div>
    }
}

list of todos come from reducer. onUpdate - function that send new position to server, server response with new list of todos. New list todos set as props to component Todos.
If server response with previous version of sorting, sortable items dont change to new positions

How to use it on a non node project

Hi Cheton, I'm not a node expert, I'm trying to use your component on a project that isn't a node project but it isn't working with the `import React from 'react' syntax.

Can you tell me how to turn it into a .js file? May I suggest you even add it to the README and the .js file to the src folder? :)

Newly rendered DOM elements not sortable

When new items are added or a set of items is replaced via new props, those new items/replaced items have not had Sortable.create called on them, and therefore their DOM elements are not sortable.

This is due to having the Sortable.create call only in componentDidMount but not also in componentDidUpdate

Cannot toggle disabled in controlled component

In a controlled component such as below in your example.
I added <Sortable options={{disabled: this.props.readonly}}....

Even though I toggle this.propsreadonly value(boolean), the Sortable component does not reflect the changes for some reason.

Is there a way to enable/disable the sortable dynamically by changing a value?

import uniqueId from 'lodash/uniqueId';
import React from 'react';
import ReactDOM from 'react-dom';
import Sortable from '../src';

class App extends React.Component {
    state = {
        items: ['Apple', 'Banana', 'Cherry', 'Guava', 'Peach', 'Strawberry']
    };

    render() {
        const items = this.state.items.map(val => (<li key={uniqueId()} data-id={val}>{val}</li>));

        return (
            <div>
                <Sortable
                    tag="ul" // Defaults to "div"
                    onChange={(order, sortable, evt) => {
                        this.setState({ items: order });
                    }}
                >
                    {items}
                </Sortable>
            </div>
        );
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('container')
);

Change list problem

Hi,

I try to put in jsFiddle

First, I drag and drop some items from SortableList1 to empty SortableList2, and then I click button to change Items in SortableList1. After doing that, the dragged item in SortableList1 did not change, and the dropped item in SortableList2 is changed.

I'm not sure what the problem is, does anyone have idea?

Thanks.

Possible to exclude items?

I know the option draggable works with Sortable, but does that translate correctly with this React implementation? I'm getting weird issues, as if the first item sometimes gets ignored.

I will try to put up a concrete example but I wanted to know if anyone had success with this already.

Update list after API call

So, not sure if I've implemented this correctly or not. However, I have a sortable list that is provided by state management (Redux). It's a numbered list of items, for example:

1. This is my first item.
2. This is my second item.
3. This is my third item.

I'm using a Controlled Component, in that I build my list from state. When an item is dragged from one position to another I'm using the onChange method to fire off an API call. An example of an updated list might be:

1. This is my second item.
2. This is my third item.
3. This is my first item. 

This updates the list on the backend, and I then update local state. This causes a render to occur, and the list flashes. I'm trying to avoid this, and wondering if I should be approaching state for the list differently?

Doesn't work in new chrome browser

Works fine in old chrome browser, in new version doesn't work. Nothing heppening. Tested it in lots of Laptops and so. Looks like onChange doesn't work

Sortable handle property

Hi @cheton, does react-sortable support the Sortable handle property?

I get the error: "Unknown prop handle on

    tag."

                                <Sortable
                                    handle=".my-handle"
                                    options={{
                                        animation: 150
                                    }}
                                    className="block-list"
                                    ref={c => {
                                        if (c) {
                                            this.simpleList = c.sortable;
                                        }
                                    }}
                                    tag="ul"
                                >
                                    {simpleList}
                                </Sortable>
    

Server side rendering error

Hello. I am attempting to use your component on a server rendered page. Everything works great except I am seeing the following warning. It is saying there is inconsistent markup. Might you know why this is occurring? Thanks!

React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server

Does not rerender elements inside <li> tags unless order is changed

Is there any way to trigger a force rerender of the Sortable component? I want to add a dropdown to each Sortable that appears when clicking on an item. My menu will not show until I change the order of items in the list. I'm not sure why it's not rendering but it seems Sortable is blocking the render. I need the dropdown to be inside the list item for positioning.

how to access the store methods in React Lifecycle methods?

Is there a way for me to call the sortable.sort() method inside a React Lifecycle method like componentDidUpdate? I can't think of an appropriate way to get the sorting order...

I've already put the data-id attribute to my sortable React components but no luck. Any clues?

Request: Access to the sortable instance

I would like to be able to call methods on the sortable instance from inside my component, which I believe means we would need to passed in the instance as a prop.

Use case: being able to set options after the fact, based on certain conditions. For example: disabling sorting based on a toggle requires a call to sortable.set('disabled', true) which necessitates access to the sortable instance.

How to use react-sortable with ui frameworks ?

Sortable component allows to define a list with html tag and css class. So if I understand things properly, the following list:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

would look somehow like that (just the render part) after making it react-sortable:

<Sortable tag="ul">
  <li key="1">One</li>
  <li key="2">Two</li>
  <li key="3">Three</li>  
</Sortable>

But in my case I pretend to use material-ui, and there a list get defined with a component and not just with a simple tag:

<List>
  <ListItem primaryText="One" />
  <ListItem primaryText="Two"  />
  <ListItem primaryText="Three" />
</List>

how can I make that react-sortable ?

onChange bug with multiple instances

I've implemented react-sortablejs on a project I'm working on and for the most part it's worked very well. However, we noticed a possible bug that may be a side effect of using multiple instances on the same page. See the following simplified example:

<div>
  <Sortable
    onChange={(order, sortable, evt) => {
      alert('first');
    }}>
    <div>1</div><div>2</div>
  </Sortable>
  <br/><br/>
  <Sortable
    onChange={(order, sortable, evt) => {
      alert('second');
    }}>
    <div>3</div><div>4</div>
  </Sortable>
</div>

Re-order the first instance (1 and 2) and an alert appears displaying 'first' as expected. However, then order the second instance (3 and 4) and an alert appears displaying 'second', then 'first' again immediately afterwards.

I've tried specifying different options.group values and also using ReactSortable instead of Sortable but no difference.

Note: we're using 1.3.6 due to breaking changes when upgrading to >=1.4.0.

Components inside dragged and cloned elements

Hi,

I have issue with dragging items between two containers.
I have Toolbar:
group: { name: 'creator', pull: 'clone', put: false },
from which i'm dragging elements to Workspace:
group: { name: 'creator', pull: true, put: true },

Inside some dragged items (div) I have other react components (fileupload - https://www.npmjs.com/package/react-fileupload). I drag (clone) element with fileupload component to Workspace and fileupload works fine. But when I drag same item from Toolbar to Workspace (clone) it does not work.
I'm new to react, but as far as I can check, when I drag (clone) item from Toolbar to Workspace, original item is appended to Workspace, and cloned item is still visible on Toolbar list, but component inside (this item in Toolbar) is already not working.
Is there any way to fix such behaviour?

Thanks.

onDrop or onEnd Event?

Cheton, thanks for the react-sortable component. Question: besides the onChange event, is there an onDrop or onSortEnd event? At the moment, I have two sortable parent containers that have child lists in them. If I drag and drop a child list within one parent, everything is fine and only one onChange event is emitted. However, when dragging a child from one parent container to another I receive two onChange events, which is not very efficient. Thus, I'd like to receive only the final event based on a "drop" event of some sort.

Any help is greatly appreciated!

Thanks!

Updating state which contains objects instead of literals

In the examples, we have state specified as an array of strings or numbers.

I have tried to use an array of objects here, something like:

        groupLeft: [{ name: 'Cat', num: 3 }, { name: 'Dog', num: 4 }],
        groupRight: [{ name: 'Mouse', num: 5 }, { name: 'Lion', num: 6 }],

        //...

        const groupLeft = this.state.groupLeft.map((obj, key) => (
            <div key={uniqueId()} data-id={obj.num}>{obj.name}</div>
        ));
        const groupRight = this.state.groupRight.map((obj, key) => (
            <div key={uniqueId()} data-id={obj.num}>{obj.name}</div>

        //...

                                onChange={(items) => {
                                    this.setState({ groupRight: items });
                                }}

Seems like it doesn't work out of the box for objects. Is that true? I'm guessing it works for literals because you can just pass that literal to data-id, and the first parameter of onChange is the order of data-ids?

Would a solution be to pass some kind of id to data-id, and then write some logic in onChange to re-arrange the objects inside of state based on those ids?

I am wondering if logic that does this might belong inside of react-sortable, since you are pretty much always going to be rearranging an array?

Thanks!

(Disclaimer: I am rather new to react and js)

UPDATE:
I was able to manipulate the order of objects in state by adding this:

import { map, find } from 'lodash';

//...

                                onChange={(order) => {
                                    const items = map(order, (num) => find(this.state.groupLeft, (o) => o.num.toString() === num));

                                    this.setState({ groupLeft: items });
                                }}

(would have to be repeated for groupRight)

Clone option throws error with React v0.14.7

When I setup two sortable lists, and group them,
with one being set to pull: 'clone'

As soon as I drag the element and drop it on the list with put: true,
The receiving list updates with the new, cloned element as expected,
but the source list gets a duplicate copy of the dropped element, and then react throws the following error: Uncaught Invariant Violation: ReactMount: Two valid but unequal nodes with the same 'data-reactid': .0.0.$5

This might be related to the unmerged fix here: SortableJS/Sortable#612

Just wondering if you're able to reproduce this, or if it's something with my setup.

Let me know if you need a jsfiddle

Passing Model via .props rather than .state / Syncing with Redux or other Flux implementation

Hello & thanks for a great component!
Working on integrating it with my project now.

One thing I'm curious about is a scenario where I'm passing my would-be model to my component via props (via Redux), but the HoC is expecting my model to be available via state.

For now, I'm going to add some glue to keep my component's state up-to-date with the props being passed in. But it seems like an anti-pattern.

Wondering if you had any thoughts or experience wiring this up to a Flux implementation?

My gut feeling is that it would be nice to specify whether the model is on state or props... Maybe something like options.modelContainer: 'props' // default: 'state'

Seems like I should be able to update Redux using an action dispatcher call using one of the provided callback options.

Anyway, thanks again.

Update: just noticed the store option... might be able to use this...

Update 2: I ended up switching to https://github.com/gaearon/react-dnd, which definitely has a little bit of a learning curve to it compared to the simplicity of react-sortable. But ultimately, I found it more flexible for what I was trying to achieve.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.