React Drag-and-Drop Sorting Guide
To utilize a drag-and-drop sorting component in React, you first need to install the necessary libraries. The most commonly used libraries are react-dnd and react-dnd-html5-backend.
- First, install these two libraries in your project:
npm install react-dnd react-dnd-html5-backend
- respond to drag-and-drop
- The source from which something can be dragged.
- Target for dropping items
import { DragSource, DropTarget } from "react-dnd";
const ItemTypes = {
CARD: "card"
};
// 创建一个DragSource
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index
};
}
};
const collectDragSource = (connect, monitor) => {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
};
// 创建一个DropTarget
const cardTarget = {
drop(props, monitor) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// 在这里可以调用一个回调函数来更新排序
props.onMove(dragIndex, hoverIndex);
}
};
const collectDropTarget = (connect, monitor) => {
return {
connectDropTarget: connect.dropTarget()
};
};
// 最终的可拖拽组件
const DraggableCard = ({ text, isDragging, connectDragSource, connectDropTarget }) => {
return connectDragSource(
connectDropTarget(
<div style={{ opacity: isDragging ? 0.5 : 1 }}>
{text}
</div>
)
);
};
export default DragSource(ItemTypes.CARD, cardSource, collectDragSource)(
DropTarget(ItemTypes.CARD, cardTarget, collectDropTarget)(DraggableCard)
);
- Create a container component to render a draggable sorting list.
import { useState } from "react";
import update from "immutability-helper";
import DraggableCard from "./DraggableCard";
const SortableList = () => {
const [cards, setCards] = useState([
{ id: 1, text: "Card 1" },
{ id: 2, text: "Card 2" },
{ id: 3, text: "Card 3" }
]);
const handleMoveCard = (dragIndex, hoverIndex) => {
const dragCard = cards[dragIndex];
setCards(
update(cards, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard]
]
})
);
};
return (
<div>
{cards.map((card, index) => (
<DraggableCard
key={card.id}
id={card.id}
index={index}
text={card.text}
onMove={handleMoveCard}
/>
))}
</div>
);
};
export default SortableList;
- List that can be sorted.
import SortableList from "./SortableList";
const App = () => {
return (
<div>
<h1>Sortable List</h1>
<SortableList />
</div>
);
};
export default App;
Now, you can use the drag-and-drop sorting component in the app. When you drag a card and drop it in another position, the list will be re-sorted.