The following configuration is not throwing any errors, but the new sort order is not being maintained. Dragging and associated animations are working well, but the sort order itself never changes permanently.
I've modified my code slightly from the example at https://www.npmjs.com/package/react-sortable-hoc. (I moved some code into a constructor function to get around an error related to experimental class properties.)
Any ideas?
import {
SortableContainer,
SortableElement,
arrayMove,
} from 'react-sortable-hoc';
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) => (
<SortableItem key={`item-${index}`} index={index} value={value} />
))}
</ul>
);
});
class SortableComponent extends Component {
constructor(props) {
super(props);
this.state = {};
this.state.items = [
"Gold",
"Crimson",
"Hotpink",
"Blueviolet",
"Cornflowerblue",
"Skyblue",
"Lightblue",
"Aquamarine",
"Burlywood"
];
this.onSortEnd = this.onSortEnd.bind(this);
}
onSortEnd(oldIndex, newIndex) {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
}
render() {
return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
}
}
The issue is in the onSortEnd callback:
onSortEnd(oldIndex, newIndex) {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
}
you need to change the arguments of the function (oldIndex, newIndex)
to be ({ oldIndex, newIndex })
from the github docs (https://github.com/clauderic/react-sortable-hoc):
onSortEnd - Callback that is invoked when sorting ends. function({oldIndex, newIndex, collection}, e)
Notice the difference in the function signature and your implementation, oldIndex
and newIndex
are being assigned by using object destructuring on the first argument. By using the second argument of the function as oldIndex
it will actually have e
as the value, which obviously cannot be used as an index when updating the order of the array!