React Dnd Kit: Drag and Drop Not Triggering for Dynamically Fetched Images

350 Views Asked by At

I'm working on a React project and attempting to implement drag-and-drop functionality using React Dnd Kit. My goal is to create a list of images that I fetch from a backend API and allow users to reorder them through drag and drop. However, I'm facing an issue where the drag events are not triggering as expected. Here's the relevant part of my code:

export const ImagesContainer = () => {
const { images } = useSelector((state) => ({
    images: state.imageStore.images
}), shallowEqual);
const [items, setItems] = useState([]);
const [activeId, setActiveId] = useState(null);
const sensors = useSensors(useSensor(MouseSensor), useSensor(TouchSensor));
useEffect(() => {
    setItems(images);
}, [images]);
function handleDragStart(event) {
    setActiveId(event.active.id);
}
function handleDragEnd(event) {
    const { active, over } = event;

    if (active.id !== over.id) {
        setItems((items) => {
            const oldIndex = items.indexOf(active.id);
            const newIndex = items.indexOf(over.id);
            return arrayMove(items, oldIndex, newIndex);
        });
    }
    setActiveId(null);
}

function handleDragCancel() {
    setActiveId(null);
}
return (
    <DndContext
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        onDragCancel={handleDragCancel}
    >
        <SortableContext items={items} strategy={rectSortingStrategy}>
            <Grid>
                {
                    items.map((image, index) =>
                        <Image key={image.id} image={image} index={index} />
                    )
                }
                <ImageUploader />
            </Grid>
        </SortableContext>
        <DragOverlay adjustScale={true}>
            {activeId ? (
                <EmptyImage url={activeId} index={items.indexOf(activeId)} />
            ) : null}
        </DragOverlay>
    </DndContext>
);

};

Problem:

The drag-and-drop events (onDragStart, onDragEnd, and onDragCancel) do not seem to be firing. What I've Tried:

I've ensured that the images are correctly fetched from the backend and stored in the items state variable. I've added unique keys to each component.

0

There are 0 best solutions below