Created
April 25, 2022 19:04
-
-
Save Terieyenike/62c9645e5dd3a68135ad0c9cc81fdabb to your computer and use it in GitHub Desktop.
This file contains 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 from "react"; | |
import { useDrag, useDrop } from "react-dnd"; | |
import galleryList from "./data.js"; | |
const Card = ({ src, title, id, index, moveImage }) => { | |
const ref = React.useRef(null); | |
const [, drop] = useDrop({ | |
accept: "image", | |
hover: (item, monitor) => { | |
if (!ref.current) { | |
return; | |
} | |
const dragIndex = item.index; | |
const hoverIndex = index; | |
if (dragIndex === hoverIndex) { | |
return; | |
} | |
const hoverBoundingRect = ref.current?.getBoundingClientRect(); | |
const hoverMiddleY = | |
(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; | |
const clientOffset = monitor.getClientOffset(); | |
const hoverClientY = clientOffset.y - hoverBoundingRect.top; | |
console.log(dragIndex, hoverIndex); | |
console.log(dragIndex < hoverIndex); | |
console.log(hoverClientY < hoverMiddleY); | |
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { | |
return; | |
} | |
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { | |
return; | |
} | |
moveImage(dragIndex, hoverIndex); | |
item.index = hoverIndex; | |
} | |
}); | |
const [{ isDragging }, drag] = useDrag({ | |
type: "image", | |
item: () => { | |
return { id, index }; | |
}, | |
collect: (monitor) => { | |
return { | |
isDragging: monitor.isDragging() | |
}; | |
} | |
}); | |
const opacity = isDragging ? 0 : 1; | |
drag(drop(ref)); | |
return ( | |
<div ref={ref} style={{ opacity }} className="card"> | |
<img src={src} alt={title} /> | |
</div> | |
); | |
}; | |
const App = () => { | |
const [images, setImages] = React.useState(galleryList); | |
const moveImage = React.useCallback((dragIndex, hoverIndex) => { | |
setImages((prevCards) => { | |
const clonedCards = [...prevCards]; | |
const removedItem = clonedCards.splice(dragIndex, 1)[0]; | |
console.log(removedItem); | |
clonedCards.splice(hoverIndex, 0, removedItem); | |
return clonedCards; | |
}); | |
}, []); | |
return ( | |
<main> | |
{React.Children.toArray( | |
images.map((image, index) => ( | |
<Card | |
src={image.img} | |
title={image.title} | |
id={image.id} | |
index={index} | |
moveImage={moveImage} | |
/> | |
)) | |
)} | |
</main> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment