Member-only story
Add Sortable Lists to our React App with React Sortable HOC
2 min readJan 10, 2021
The React Sortable HOC library lets us add sortable lists to our React app.
In this article, we’ll look at how to use it to add the lists.
Installation
We install the library by running:
npm install react-sortable-hoc --save
Sortable List
We can use the library to create a sortable list by writing:
import React from "react";
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 React.Component {
state = {
items: Array(6)
.fill()
.map((_, i) => `item ${i}`)
};
onSortEnd = ({ oldIndex, newIndex }) => {
this.setState(({ items }) => ({
items: arrayMove(items, oldIndex, newIndex)
}));
};
render() {
return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
}
}
export default…