Example of sortable list on React based on HTML Drag and Drop API
interface Item {
title: string
}
function App() {
const [items, setItems] = useState<Item[]>([
{ title: 'item #1'},
{ title: 'item #2'},
{ title: 'item #3'},
{ title: 'item #4'},
{ title: 'item #5'},
])
const sortHandler = useCallback((sourceIndex: number, targetIndex: number) => {
if (sourceIndex === targetIndex) {
return
}
setItems(originItems => {
const items = originItems.slice()
const item = items[sourceIndex]
items.splice(sourceIndex, 1)
items.splice(targetIndex, 0 ,item)
return items
})
}, [setItems])
return (
<SortableList items={items} onSort={sortHandler}>
{props => <ItemVerticalComponent {...props} />}
</SortableList>
)
};
Project was created during youtube stream in collaboration with Tim Khazamov