To implement drag-and-drop functionality in React, follow these steps:
react-dnd
and react-dnd-html5-backend
packages using npm or yarn:npm install react-dnd
npm install react-dnd-html5-backend
useDrag
hook from react-dnd
. Here's an example of a draggable component:import { useDrag } from 'react-dnd';
const DraggableItem = ({ text }) => {
const [{ isDragging }, drag] = useDrag({
type: 'DRAGGABLE_ITEM',
item: { text },
collect: monitor => ({
isDragging: !!monitor.isDragging(),
}),
});
return (
<div
ref={drag}
style={{
opacity: isDragging ? 0.5 : 1,
cursor: 'move',
}}
>
{text}
</div>
);
};
export default DraggableItem;
useDrop
hook from react-dnd
. Here's an example of a drop target component:import { useDrop } from 'react-dnd';
const DropTarget = ({ onDrop }) => {
const [{ isOver }, drop] = useDrop({
accept: 'DRAGGABLE_ITEM',
drop: item => onDrop(item),
collect: monitor => ({
isOver: !!monitor.isOver(),
}),
});
return (
<div
ref={drop}
style={{
border: isOver ? '2px solid red' : 'none',
minHeight: '100px',
}}
>
Drop here
</div>
);
};
export default DropTarget;
import DraggableItem from './DraggableItem';
import DropTarget from './DropTarget';
const App = () => {
const handleDrop = item => {
console.log('Item dropped:', item);
};
return (
<div>
<DraggableItem text="Item 1" />
<DraggableItem text="Item 2" />
<DropTarget onDrop={handleDrop} />
</div>
);
};
export default App;