Your implementation using the @dnd-kit library for drag-and-drop functionality in a Next.js 14 application with TypeScript is well-structured and demonstrates a solid understanding of both React and the @dnd-kit API. However, there are a few areas that could be refined to enhance functionality, maintainability, and performance. Below is an in-depth analysis of your code, highlighting key features, potential issues, and recommendations for improvement.
1. Unique Identifier Management
Issue:
- Using
file.name as Unique Identifiers:
- Problem: Leveraging
file.name as the UniqueIdentifier for sortable items can lead to duplicate IDs if multiple files share the same name, especially across different containers. This can cause unpredictable behavior in the drag-and-drop functionality.
Recommendation:
-
Generate Truly Unique IDs:
- Solution: Instead of relying on
file.name, generate unique identifiers for each file. You can achieve this by extending the imagesArray structure to include a unique ID for each file. Libraries like uuid can help generate these IDs.
import { v4 as uuidv4 } from 'uuid';
interface IImage {
id: string;
file: File;
}
interface IProps {
containers: IContainer[];
imagesArray: IImage[][];
setImagesArray: React.Dispatch<React.SetStateAction<IImage[][]>>;
}
// When adding files to imagesArray:
const newImages = files.map((file) => ({ id: uuidv4(), file }));
setImagesArray((prev) => [...prev, newImages]);
-
Update Components Accordingly:
- Modify
SortableImage and related components to use the new id field.
const SortableImage: React.FC<SortableImageProps> = ({ image, index, containerId, onDelete }) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
id: image.id,
data: { type: "image", containerId, index },
});
// Rest of the component remains the same, using image.file instead of file
};
2. Managing Object URLs Efficiently
Issue:
- Using
URL.createObjectURL Directly in Render:
- Problem: Calling
URL.createObjectURL(file) within the render method can lead to memory leaks since the URLs are not revoked. Additionally, it can cause unnecessary re-creations of URLs on every render, impacting performance.
Recommendation:
-
Use useEffect to Manage Object URLs:
- Solution: Generate the object URL once per file and revoke it when the component unmounts or when the file changes.
import React, { useState, useEffect } from "react";
const SortableImage: React.FC<SortableImageProps> = ({ image, index, containerId, onDelete }) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
id: image.id,
data: { type: "image", containerId, index },
});
const [imageUrl, setImageUrl] = useState<string>("");
useEffect(() => {
const url = URL.createObjectURL(image.file);
setImageUrl(url);
return () => URL.revokeObjectURL(url);
}, [image.file]);
const style = { transform: CSS.Transform.toString(transform), transition };
return (
<div className="relative flex shrink-0 border">
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className="relative w-fit h-fit cursor-grab"
>
<Image src={imageUrl} height={240} width={240} alt={`Image ${index}`} className="h-fit w-60" unoptimized />
</div>
<Button
onClick={() => onDelete(containerId, index)}
variant="destructive"
size="icon"
className="top-1 right-1 absolute opacity-20 hover:opacity-60"
>
<XIcon className="h-5 w-5" />
</Button>
</div>
);
};
3. Handling Drag Events Robustly
Issue:
- Potential Redundancy in
overContainerId Assignment:
- Problem: In the
handleDragEnd function, the line const overContainerId = overData.type === "container" ? overData.containerId : overData.containerId; is redundant since both cases assign the same value.
Recommendation:
-
Simplify the Assignment:
- Solution: Remove the unnecessary conditional and directly assign
overData.containerId.
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over) return;
const activeData = active.data.current as { type: string; containerId: number; index?: number };
const overData = over.data.current as { type: string; containerId: number; index?: number };
if (!activeData || !overData) return;
const activeContainerId = activeData.containerId;
const overContainerId = overData.containerId;
if (typeof activeContainerId !== "number" || typeof overContainerId !== "number") return;
setImagesArray((prevImagesArray) => {
const activeContainer = prevImagesArray[activeContainerId];
if (!activeContainer) return prevImagesArray;
const activeIndex = activeContainer.findIndex((image) => image.id === active.id);
if (activeIndex === -1) return prevImagesArray;
const newImagesArray = [...prevImagesArray];
if (activeContainerId === overContainerId) {
// Moving within the same container
const overIndex =
overData.type === "container"
? newImagesArray[overContainerId].length
: (overData.index ?? newImagesArray[overContainerId].length);
newImagesArray[activeContainerId] = arrayMove(newImagesArray[activeContainerId], activeIndex, overIndex);
} else {
// Moving between containers
const [movedItem] = newImagesArray[activeContainerId].splice(activeIndex, 1);
if (overData.type === "container") {
// Dropping onto a container
newImagesArray[overContainerId].push(movedItem);
} else {
// Dropping onto an image in another container
const overIndex = overData.index ?? newImagesArray[overContainerId].length;
newImagesArray[overContainerId].splice(overIndex, 0, movedItem);
}
}
return newImagesArray;
});
setActiveId(null);
};
-
Enhance Type Safety:
- Ensure that
activeData and overData are correctly typed to prevent runtime errors.
const activeData = active.data.current as { type: "image" | "container"; containerId: number; index?: number };
const overData = over.data.current as { type: "image" | "container"; containerId: number; index?: number };
4. Optimizing React Keys for List Rendering
Issue:
- Using Array Indices as Keys:
- Problem: In the
ImagesContainers component, additional ImagesContainer components use key={index + 1}. Using indices as keys can lead to rendering issues, especially if the list can change order or items can be added/removed.
Recommendation:
-
Use Unique and Stable Keys:
- Solution: Utilize
containerId as the key since it's inherently unique and stable.
{imagesArray.slice(1).map((images, index) => (
<ImagesContainer
key={index + 1} // Change this to key={index + 1} if containerId is not directly available
// Alternatively, if containerId is unique and available:
// key={`container-${containerId}`}
direction="horizontal"
className="h-full w-full overflow-x-auto overflow-y-hidden"
label={containers[index].label}
images={images}
containerId={index + 1}
onDelete={handleDelete}
/>
))}
- Preferred Approach: If
containerId is unique and accessible, use it directly as the key.
{imagesArray.slice(1).map((images, index) => {
const containerId = index + 1;
return (
<ImagesContainer
key={containerId}
direction="horizontal"
className="h-full w-full overflow-x-auto overflow-y-hidden"
label={containers[index].label}
images={images}
containerId={containerId}
onDelete={handleDelete}
/>
);
})}
5. Enhancing Performance with Memoization
Issue:
- Potential Unnecessary Re-renders:
- Problem: Components like
SortableImage and ImagesContainer may re-render unnecessarily, especially when dealing with large lists of images.
Recommendation:
-
Use React.memo to Prevent Unnecessary Re-renders:
- Solution: Wrap child components with
React.memo to optimize rendering performance.
import React, { memo } from "react";
const SortableImage: React.FC<SortableImageProps> = memo(({ image, index, containerId, onDelete }) => {
// Component implementation
});
const ImagesContainer: React.FC<ImagesContainerProps> = memo(({ direction, className, label, images, containerId, onDelete }) => {
// Component implementation
});
-
Ensure Stable Props:
- Ensure that the props passed to memoized components are stable (i.e., references don't change unnecessarily) to maximize the benefits of memoization.
6. Ensuring Accessibility
Issue:
- Keyboard Navigation and ARIA Attributes:
- Problem: While
@dnd-kit provides keyboard support, enhancing accessibility with ARIA attributes can improve the user experience for individuals relying on assistive technologies.
Recommendation:
-
Add ARIA Attributes:
- Solution: Incorporate ARIA attributes to convey additional information about draggable and droppable elements.
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className="relative w-fit h-fit cursor-grab"
role="button"
aria-grabbed={isDragging}
aria-label={`Image ${index + 1}`}
>
{/* Image Component */}
</div>
-
Provide Visual Focus Indicators:
- Ensure that focusable elements have clear visual indicators when focused via keyboard navigation.
7. Code Cleanliness and Maintainability
Issue:
- Complex Conditional Class Names:
- Problem: Conditional class names can become hard to read and maintain, especially with nested ternary operators.
Recommendation:
-
Use Utility Functions or Libraries:
- Solution: Utilize utility functions like
clsx or continue with your cn function to handle complex class name logic more cleanly.
import clsx from 'clsx';
<div
className={clsx(
"min-h-80 min-w-64 flex flex-col shrink-0 overflow-hidden border rounded",
direction === "vertical"
? "h-full w-fit"
: images.length === 0
? "h-fit w-fit"
: "h-fit w-full"
)}
>
{/* Rest of the component */}
</div>
8. TypeScript Enhancements
Issue:
- Type Assertions and Safety:
- Problem: In
handleDragEnd, type assertions like active.data.current as { type: string; containerId: number; index?: number } can bypass TypeScript's type checking, leading to potential runtime errors.
Recommendation:
-
Define and Use Specific Types:
- Solution: Create specific interfaces for
activeData and overData to leverage TypeScript's type safety fully.
interface DragData {
type: "image" | "container";
containerId: number;
index?: number;
}
const activeData = active.data.current as DragData;
const overData = over.data.current as DragData;
- Optional: Use runtime type checking (e.g., with
zod or io-ts) to validate the structure of activeData and overData.
9. Handling Edge Cases
Issue:
- Dropping onto Non-Image and Non-Container Areas:
- Problem: If a user attempts to drop an item onto an area that is neither a container nor an image, the current implementation may not handle it gracefully.
Recommendation:
10. Additional Best Practices
-
Avoid Inline Functions:
- Pass stable callback references to child components to prevent unnecessary re-renders.
const handleDelete = useCallback((containerId: number, index: number) => {
setImagesArray((prevImagesArray) => {
const newImagesArray = [...prevImagesArray];
newImagesArray[containerId] = [
...newImagesArray[containerId].slice(0, index),
...newImagesArray[containerId].slice(index + 1),
];
return newImagesArray;
});
}, [setImagesArray]);
-
Consistent Naming Conventions:
- Ensure that variable and function names are consistent and descriptive to improve code readability.
-
Comprehensive Error Handling:
- Extend error handling to cover more scenarios and provide meaningful feedback to users when operations fail.
Revised Code Snippets
Below are revised snippets incorporating the recommendations mentioned above:
SortableImage Component with Unique IDs and Managed Object URLs
import React, { useState, useEffect, memo } from "react";
import Image from "next/image";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
interface IImage {
id: string;
file: File;
}
interface SortableImageProps {
image: IImage;
index: number;
containerId: number;
onDelete: (containerId: number, index: number) => void;
}
const SortableImage: React.FC<SortableImageProps> = memo(({ image, index, containerId, onDelete }) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
id: image.id,
data: { type: "image", containerId, index },
});
const [imageUrl, setImageUrl] = useState<string>("");
useEffect(() => {
const url = URL.createObjectURL(image.file);
setImageUrl(url);
return () => URL.revokeObjectURL(url);
}, [image.file]);
const style = { transform: CSS.Transform.toString(transform), transition };
return (
<div className="relative flex shrink-0 border">
<div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className="relative w-fit h-fit cursor-grab"
role="button"
aria-grabbed={false} // Update if tracking drag state
aria-label={`Image ${index + 1}`}
>
<Image src={imageUrl} height={240} width={240} alt={`Image ${index}`} className="h-fit w-60" unoptimized />
</div>
<Button
onClick={() => onDelete(containerId, index)}
variant="destructive"
size="icon"
className="top-1 right-1 absolute opacity-20 hover:opacity-60"
aria-label={`Delete image ${index + 1}`}
>
<XIcon className="h-5 w-5" />
</Button>
</div>
);
});
export default SortableImage;
ImagesContainer Component
import React, { memo } from "react";
import { useSortable, SortableContext, arrayMove, verticalListSortingStrategy, horizontalListSortingStrategy } from "@dnd-kit/sortable";
import { IImage } from "./SortableImage";
import SortableImage from "./SortableImage";
import { cn } from "@/lib/utils";
interface ImagesContainerProps {
direction: "vertical" | "horizontal";
className: string;
label?: string;
images: IImage[];
containerId: number;
onDelete: (containerId: number, index: number) => void;
}
const ImagesContainer: React.FC<ImagesContainerProps> = memo(({ direction, className, label, images, containerId, onDelete }) => {
const { setNodeRef } = useSortable({
id: `container-${containerId}`,
data: { type: "container", containerId },
});
return (
<div
ref={setNodeRef}
className={`min-h-80 min-w-64 flex flex-col shrink-0 overflow-hidden border rounded ${
direction === "vertical" ? "h-full w-fit" : images.length === 0 ? "h-fit w-fit" : "h-fit w-full"
}`}
role="list"
aria-label={label || `Container ${containerId}`}
>
{!!label && <h3 className="h-12 flex items-center font-medium px-4">{label}</h3>}
<div className={cn("flex gap-4 p-4", className)} role="group">
<SortableContext
items={images.map((image) => image.id)}
strategy={direction === "vertical" ? verticalListSortingStrategy : horizontalListSortingStrategy}
>
{images.map((image, index) => (
<SortableImage key={image.id} image={image} index={index} containerId={containerId} onDelete={onDelete} />
))}
</SortableContext>
</div>
</div>
);
});
export default ImagesContainer;
ImagesContainers Component with Enhanced handleDragEnd
import React, { useState, useCallback } from "react";
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragOverlay } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy, horizontalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import ImagesContainer from "./ImagesContainer";
import { IContainer } from ".";
import { cn } from "@/lib/utils";
interface IImage {
id: string;
file: File;
}
interface IProps {
containers: IContainer[];
imagesArray: IImage[][];
setImagesArray: React.Dispatch<React.SetStateAction<IImage[][]>>;
}
const ImagesContainers: React.FC<IProps> = ({ containers, imagesArray, setImagesArray }) => {
const [activeId, setActiveId] = useState<string | null>(null);
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
);
const handleDragStart = useCallback((event: any) => {
setActiveId(event.active.id);
}, []);
const handleDragEnd = useCallback((event: any) => {
const { active, over } = event;
if (!over) {
setActiveId(null);
return;
}
const activeData = active.data.current as { type: "image" | "container"; containerId: number; index?: number };
const overData = over.data.current as { type: "image" | "container"; containerId: number; index?: number };
if (!activeData || !overData) {
setActiveId(null);
return;
}
const activeContainerId = activeData.containerId;
const overContainerId = overData.containerId;
if (typeof activeContainerId !== "number" || typeof overContainerId !== "number") {
setActiveId(null);
return;
}
setImagesArray((prevImagesArray) => {
const activeContainer = prevImagesArray[activeContainerId];
if (!activeContainer) return prevImagesArray;
const activeIndex = activeContainer.findIndex((image) => image.id === active.id);
if (activeIndex === -1) return prevImagesArray;
const newImagesArray = [...prevImagesArray];
if (activeContainerId === overContainerId) {
// Moving within the same container
const overIndex =
overData.type === "container"
? newImagesArray[overContainerId].length
: overData.index ?? newImagesArray[overContainerId].length;
newImagesArray[activeContainerId] = arrayMove(newImagesArray[activeContainerId], activeIndex, overIndex);
} else {
// Moving between containers
const [movedItem] = newImagesArray[activeContainerId].splice(activeIndex, 1);
if (overData.type === "container") {
// Dropping onto a container
newImagesArray[overContainerId].push(movedItem);
} else {
// Dropping onto an image in another container
const overIndex = overData.index ?? newImagesArray[overContainerId].length;
newImagesArray[overContainerId].splice(overIndex, 0, movedItem);
}
}
return newImagesArray;
});
setActiveId(null);
}, [setImagesArray]);
const handleDelete = useCallback((containerId: number, index: number) => {
setImagesArray((prevImagesArray) => {
const newImagesArray = [...prevImagesArray];
newImagesArray[containerId] = [
...newImagesArray[containerId].slice(0, index),
...newImagesArray[containerId].slice(index + 1),
];
return newImagesArray;
});
}, [setImagesArray]);
const activeFile = activeId ? imagesArray.flat().find((image) => image.id === activeId)?.file : null;
const activeImageUrl = activeFile ? URL.createObjectURL(activeFile) : null;
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
<div className="h-full w-full flex overflow-hidden gap-8 pl-8 pb-8 lg:pl-24">
<ImagesContainer
key={0}
direction={imagesArray.length > 1 ? "vertical" : "horizontal"}
className={`h-full ${imagesArray.length > 1 ? "min-w-60 w-fit flex-col" : "w-full flex-wrap"} overflow-x-hidden overflow-y-auto`}
label={imagesArray.length > 1 ? "Staging" : undefined}
images={imagesArray[0]}
containerId={0}
onDelete={handleDelete}
/>
{imagesArray.length > 1 && (
<div className="h-full w-full flex flex-wrap overflow-x-hidden content-start overflow-y-auto gap-8 pr-8 lg:pr-24">
{imagesArray.slice(1).map((images, index) => {
const containerId = index + 1;
return (
<ImagesContainer
key={containerId}
direction="horizontal"
className="h-full w-full overflow-x-auto overflow-y-hidden"
label={containers[index].label}
images={images}
containerId={containerId}
onDelete={handleDelete}
/>
);
})}
</div>
)}
</div>
<DragOverlay>
{activeFile && activeImageUrl && (
<div className="relative h-fit w-fit opacity-50 hover:cursor-grabbing transition-none">
<Image
src={activeImageUrl}
height={160}
width={160}
alt="Dragging"
className="h-fit w-40 flex shrink-0 border"
unoptimized
/>
</div>
)}
</DragOverlay>
</DndContext>
);
};
export default ImagesContainers;
Conclusion
Your solution effectively leverages the @dnd-kit library to implement a flexible and interactive image sorting interface. By addressing the highlighted areas—particularly around unique identifier management and object URL handling—you can enhance the robustness and performance of your application. Implementing these recommendations will lead to a more maintainable, efficient, and user-friendly drag-and-drop experience.
If you have any specific questions or need further assistance with particular parts of your code, feel free to ask!