I want to use a React sorting library called, React Sortable HOC. It seems like a great library, but I'm having trouble trying to figure out how to use it in my instance.
I set it up like one of the examples they provided:
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>
);
});
const onSortEnd = ({ oldIndex, newIndex }) => {
this.setState(({ items }) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
In the example, they map it from state like this:
return (
<SortableContainer onSortEnd={this.onSortEnd}>
{items.map((value, index) => (
<SortableItem key={`item-${value}`} index={index} value={value} />
))}
</SortableContainer>
);
But in my case, I am using 'map' to go through my state item(starships) and generating my data like this:
return (
<div>
{starships.map((starShip) => (
<Ship starShip={starShip} />
))}
</div>
);
Where Ship is this element:
const Ship = ({ ship: { ShipId, ShipName } }) => (
<tr key={ShipId}>
<td>{ShipNameName}</td>
</tr>
);
I can't figure out how I'd use this library with the way I have my application set up.
Is there anyone who has used it like this?
Thanks!
Here is an example of how you can use it:
const { SortableContainer, SortableElement } = SortableHOC;
const arrayMoveMutate = (array, from, to) => {
array.splice(
to < 0 ? array.length + to : to,
0,
array.splice(from, 1)[0]
);
};
const arrayMove = (array, from, to) => {
array = array.slice();
arrayMoveMutate(array, from, to);
return array;
};
function App() {
const [ships, setShips] = React.useState([
{ ShipName: 'ship a', ShipId: 1 },
{ ShipName: 'ship b', ShipId: 2 },
{ ShipName: 'ship c', ShipId: 3 },
]);
const onSortEnd = React.useCallback(
({ oldIndex, newIndex }) => {
setShips(ships =>
arrayMove(ships, oldIndex, newIndex)
);
},
[]
);
return (
<SortableList items={ships} onSortEnd={onSortEnd} />
);
}
const SortableList = SortableContainer(({ items }) => {
return (
<ul>
{items.map((ship, index) => (
<Ship
key={ship.ShipId}
index={index}
value={ship}
/>
))}
</ul>
);
});
const Ship = SortableElement(
({ value }) => <li>{value.ShipName}</li>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-sortable-hoc/0.9.0/react-sortable-hoc.min.js"></script>