Skip to content

Instantly share code, notes, and snippets.

@flpsoares
Last active September 13, 2021 12:04
Show Gist options
  • Save flpsoares/a077e38060c18e61ecda73f6c73cfe2e to your computer and use it in GitHub Desktop.
Save flpsoares/a077e38060c18e61ecda73f6c73cfe2e to your computer and use it in GitHub Desktop.
Drag and drop
public async updateAll({ request }: HttpContextContract) {
const {items} = request.all()
return await Link.updateOrCreateMany(['title'], items)
}
import {
DragDropContext,
Droppable,
Draggable,
DropResult
} from 'react-beautiful-dnd'
function App() {
const [links, setLinks] = useState<LinkProps[]>([])
useEffect(() => {
api.get('links').then((res) => {
setLinks(res.data)
setLinkLength(res.data.length)
})
}, [linkLength, linkUpdated])
const handleOnDragEnd = (result: DropResult) => {
if (!result.destination) return
const items = Array.from(links)
const [reorderedItem] = items.splice(result.source.index, 1)
items.splice(result.destination.index, 0, reorderedItem)
api.put('link', {
items: items.map((item, index) => {
return {
title: item.title,
order: index
}
})
})
setLinks(items)
}
return (
<AnimatePresence>
<Container>
<DragDropContext onDragEnd={handleOnDragEnd}>
<Droppable droppableId="links">
{(provided) => {
return (
<div {...provided.droppableProps} ref={provided.innerRef}>
{links.map((link, index) => {
return (
<Draggable
key={link.id}
draggableId={String(link.id)}
index={index}
>
{(provided) => {
return (
<div
{...provided.draggableProps}
{...provided.dragHandleProps}
ref={provided.innerRef}
>
<Link
title={link.title}
url={link.url}
icon={link.icon}
views={link.views}
/>
</div>
)
}}
</Draggable>
)
})}
{provided.placeholder}
</div>
)
}}
</Droppable>
</DragDropContext>
</Container>
</AnimatePresence>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment