Last active
November 26, 2024 06:30
-
-
Save ali-master/95aa60e6184bdfb85631d8f911e45251 to your computer and use it in GitHub Desktop.
React Drag and Drop with indicator(Swap)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState} from "react"; | |
export const DragAndDrop = () => { | |
const cardData = [ | |
{ | |
id: 1, | |
image: "https://i.ibb.co.com/XxvZ2Kq/Logo.png" | |
}, | |
{ | |
id: 2, | |
image: "https://i.ibb.co.com/HgvwbMy/Logo-1.png" | |
}, | |
{ | |
id: 3, | |
image: "https://i.ibb.co.com/XS8kxJF/Logo-2.png" | |
}, | |
{ | |
id: 4, | |
image: "https://i.ibb.co.com/2gLx39W/Logo-3.png" | |
}, | |
{ | |
id: 5, | |
image: "https://i.ibb.co.com/DkDCXrk/Logo-4.png" | |
}, | |
{ | |
id: 6, | |
image: "https://i.ibb.co.com/W0qf3ZP/Amazon.png" | |
}, | |
{ | |
id: 7, | |
image: "https://i.ibb.co.com/fp0pFV5/Logo-5.png" | |
}, | |
{ | |
id: 8, | |
image: "https://i.ibb.co.com/S3Z98YZ/Logo-6.png" | |
}, | |
{ | |
id: 9, | |
image: "https://i.ibb.co.com/0FwfDsz/Union.png" | |
}, | |
]; | |
const [gridItems, setGridItems] = useState(cardData); | |
const [draggedItem, setDraggedItem] = useState(null); | |
const [hoveredItem, setHoveredItem] = useState(null); | |
// Handle drag start event | |
const handleDragStart = (item) => { | |
setDraggedItem(item); | |
}; | |
// Handle drag over event and show hover indicator | |
const handleDragOver = (e, item) => { | |
e.preventDefault(); | |
setHoveredItem(item); | |
}; | |
// Handle drop event and swap items | |
const handleDrop = (e, dropItem) => { | |
e.preventDefault(); | |
// Swap dragged item with drop target | |
const newGrid = gridItems.map((item) => { | |
if (item.id === dropItem.id) { | |
return draggedItem; | |
} | |
if (item.id === draggedItem.id) { | |
return dropItem; | |
} | |
return item; | |
}); | |
setGridItems(newGrid); | |
setDraggedItem(null); | |
setHoveredItem(null); | |
}; | |
return ( | |
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4"> | |
{gridItems.map((item) => ( | |
<div | |
key={item.id} | |
draggable | |
onDragStart={() => handleDragStart(item)} | |
onDragOver={(e) => handleDragOver(e, item)} | |
onDrop={(e) => handleDrop(e, item)} | |
onDragLeave={() => setHoveredItem(null)} | |
className={`w-full px-8 py-4 border-2 rounded text-center cursor-move ${ | |
item.id === draggedItem?.id && "bg-blue-100 opacity-30" | |
} ${ | |
item.id === hoveredItem?.id ? "border-dashed border-2 border-blue-500" : "border-gray-100" | |
}`} | |
> | |
<img alt="image" src={item.image} | |
className="w-[100px] sm:w-[140px] h-[50px] object-contain"/> | |
</div> | |
))} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment