I am creating a project when I drag and drop an image into another image it switches its place.
I need a way to move the image itself while dragging it and it should also replace with the target image(where it is dropped).
function MainGroup (){
const intialImg = [
{ id: 1, name: "BOX1", src: Mercury },
{ id: 2, name: "BOX2", src:Venus },
{ id: 3, name: "BOX3", src:Earth },
{ id: 4, name: "BOX4", src:Mars },
{ id: 5, name: "BOX5", src:Jupiter },
{ id: 6, name: "BOX6", src:Saturn },
{ id: 7, name: "BOX7", src:Uranus },
{ id: 8, name: "BOX8", src:Neptune },
{ id: 9, name: "BOX9", src:Pluto },
{ id: 10, name: "BOX10", src:Ast1 },
{ id: 11, name: "BOX11", src:Ast2 },
{ id: 12, name: "BOX12", src:Ast3 },
{ id: 13, name: "BOX13", src:Ast4 },
{ id: 14, name: "BOX14", src:Ast5 },
{ id: 15, name: "BOX15", src:Ast6 },
{ id: 16, name: "BOX16", src:Ast7 }
]
const [images, setImages] = useState([])
const [counter, setCounter] = useState(0)
if(images.length === 0)
{
setImages(intialImg)
}
const handleStart = data => e => {
if(!data) return;
let fImg = JSON.stringify({ id: data.id });
e.dataTransfer.setData("draggedImg", fImg);
};
const handleStop = data => e => {
e.preventDefault();
return false;
};
const handleDrop = data => e => {
e.preventDefault();
let fImg = JSON.parse(e.dataTransfer.getData("draggedImg"));
let toImg = { id: data.id };
swapImages(fImg, toImg);
return false;
};
const swapImages = (fromImg, toImg) => {
let tempImg = images;
let fIndex = -1;
let tIndex = -1;
for (let i = 0; i < tempImg.length; i++) {
if (tempImg[i].id === fromImg.id) {
fIndex = i;
}
if (tempImg[i].id === toImg.id) {
tIndex = i;
}
}
if (fIndex !== -1 && tIndex !== -1) {
let { fromId, ...fromRest } = tempImg[fIndex];
let { toId, ...toRest } = tempImg[tIndex];
tempImg[fIndex] = { id: fromImg.id, ...toRest };
tempImg[tIndex] = { id: toImg.id, ...fromRest };
setImages(tempImg)
setCounter(counter => counter + 1)
console.log(images)
}
};
return (
<div>
<h1>{counter}</h1>
<div className="boxesGroup" >
{images.map(image =>
<img
key={image.id}
className="box"
src={image.src}
alt={image.id}
onDragStart={handleStart({id: image.id})}
onDragOver={handleStop({id: image.id})}
onDrop={handleDrop({id: image.id})} >
</img>
)}
</div>
</div>
)
}
export default MainGroup;
This is the entire react code which swaps the images on drag and drop.
The image shows the image being dragged but its ghost preview is only being dragged. I need the image to drag along with the cursor