This is a simple React example demonstrating how to implement drag-and-drop sorting using react-dnd
. It allows users to reorder a list of items by dragging and dropping.
react-dnd
Integration: Utilizes react-dnd
to manage drag-and-drop operations efficiently.DndContainer
The DndContainer
manages the list of draggable items. It listens for drag-and-drop events and updates the order of items when they are moved.
<DndContainer data={data} onChange={handleChange} />
The DndCard
component represents an individual draggable item within the DndContainer
. Each card can be moved and reordered by dragging it.
<Card key={card.id} index={i} id={card.id} text={card.text} moveCard={moveCard} />
To use the drag-and-drop functionality, simply pass a list of items (data
) to the DndContainer
:
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { DndContainer } from "./DndContainer";
const data = [
{ id: 1, text: "Widget1" },
{ id: 2, text: "Chart" },
{ id: 3, text: "Calculator" },
{ id: 4, text: "Stocks" },
{ id: 5, text: "Calendar" },
];
function App() {
return (
<DndProvider backend={HTML5Backend}>
<DndContainer data={data} />
</DndProvider>
);
}
data
: An array of items to display. Each item must have an id
and text
.onChange
: A callback function that receives the updated list of items after reordering.