How to implement drag-and-drop in React?

To implement drag-and-drop functionality in React, follow these steps:

  1. Install the react-dnd and react-dnd-html5-backend packages using npm or yarn:
npm install react-dnd npm install react-dnd-html5-backend
  1. Create a draggable component using the 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;
  1. Create a drop target component using the 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;
  1. Use the draggable and drop target components in your main React component:
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;
  1. Run your React application and test the drag-and-drop functionality. You should be able to drag the draggable items and drop them onto the drop target.