To implement drag-and-drop functionality in Next.js, you can use the react-dnd
library, which provides a set of React hooks for drag-and-drop interactions. The useDrag
and useDrop
hooks are part of this library and are used to create draggable and droppable components, respectively.
Here's a basic example of how you can use these hooks in a Next.js project:
bashnpm install react-dnd react-dnd-html5-backend
DraggableItem.js
):jsximport { useDrag } from 'react-dnd';
const DraggableItem = ({ item, index }) => {
const [, drag] = useDrag({
item: { type: 'ITEM', index },
});
return (
<div ref={drag} style={{ border: '1px solid #ccc', padding: '8px', marginBottom: '8px' }}>
{item}
</div>
);
};
export default DraggableItem;
DropTarget.js
):jsximport { useDrop } from 'react-dnd';
const DropTarget = ({ onDrop, children }) => {
const [, drop] = useDrop({
accept: 'ITEM',
drop: onDrop,
});
return <div ref={drop}>{children}</div>;
};
export default DropTarget;
pages/index.js
):jsximport { useState } from 'react';
import DraggableItem from '../components/DraggableItem';
import DropTarget from '../components/DropTarget';
const DragAndDropPage = () => {
const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);
const handleDrop = (originalIndex, newIndex) => {
const newItems = [...items];
const [removed] = newItems.splice(originalIndex, 1);
newItems.splice(newIndex, 0, removed);
setItems(newItems);
};
return (
<div>
<DropTarget onDrop={handleDrop}>
{items.map((item, index) => (
<DraggableItem key={index} item={item} index={index} />
))}
</DropTarget>
</div>
);
};
export default DragAndDropPage;
In this example, the DraggableItem
component represents each draggable item, and the DropTarget
component is the area where items can be dropped. The handleDrop
function updates the state to reflect the new order of items after a drop event.
Make sure to import and use these components appropriately in your application. Additionally, you might need to configure the styles and appearance based on your design requirements.