Implementing Drag & Drop in Next.js

Drag and drop functionality enhances user experience by making interactions more intuitive. In this tutorial, we'll explore how to implement a drag-and-drop feature in a Next.js application using the @hello-pangea/dnd library.

Implementing Drag & Drop in Next.js

Introduction

Drag and drop functionality enhances user experience by making interactions more intuitive. In this tutorial, we’ll explore how to implement a drag-and-drop feature in a Next.js application using the @hello-pangea/dnd library.

Prerequisites

Before we begin, ensure that you have the following installed:

Step 1: Install Dependencies

First, install the @hello-pangea/dnd package by running:

npm install @hello-pangea/dnd

or

yarn add @hello-pangea/dnd

Step 2: Create a Drag & Drop Component

Now, let’s create a simple drag-and-drop feature to reorder a list of items.

Full Code Implementation

Below is the complete Next.js component implementing drag-and-drop functionality.

"use client";

import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { useState } from "react";

interface Item {
  title: string;
  description: string;
}

export default function Home() {
  const [data, setData] = useState<Item[]>([
    { title: "Item 1", description: "Description 1" },
    { title: "Item 2", description: "Description 2" },
    { title: "Item 3", description: "Description 3" },
  ]);

  const onDragEnd = (result: any) => {
    if (!result.destination) return;

    const reorderedData = [...data];
    const [movedItem] = reorderedData.splice(result.source.index, 1);
    reorderedData.splice(result.destination.index, 0, movedItem);

    setData(reorderedData);
  };

  return (
    <div className="container mx-auto px-[20px] py-[20px]">
      <h1 className="font-bold lg:text-[32px] text-[24px]">Drag & Drop</h1>
      <div className="grid grid-cols-1 gap-[20px] mt-[40px]">
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="questions">
            {(provided) => (
              <div
                {...provided.droppableProps}
                ref={provided.innerRef}
                className="space-y-4"
              >
                {data.map((item, index) => (
                  <Draggable key={item.title} draggableId={item.title} index={index}>
                    {(provided) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                        className="cursor-grab border border-gray-200 p-[20px] rounded-[10px]"
                      >
                        <h2 className="font-bold lg:text-[24px] text-[18px]">
                          {item.title}
                        </h2>
                        <p className="text-[16px]">{item.description}</p>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </div>
    </div>
  );
}

Step 3: Breakdown of the Code

1. State Management

We define a state variable data using useState to store the list of draggable items.

2. Handling Drag & Drop Events

The onDragEnd function is triggered when a drag operation ends. It reorders the list based on the new positions of the dragged items.

3. Using DragDropContext

The <DragDropContext> component wraps the draggable elements and listens for drag-and-drop events.

4. Using Droppable

The <Droppable> component defines an area where draggable items can be dropped.

5. Using Draggable

Each item in the list is wrapped inside a <Draggable> component, enabling it to be dragged.

Step 4: Styling the Components

We use Tailwind CSS classes for styling:

Conclusion

This tutorial covered implementing drag-and-drop functionality in Next.js using @hello-pangea/dnd. You can now integrate this feature into your projects to enhance user interactions. Try modifying the code to handle different data structures or implement additional drag-and-drop features!

Source Code: https://github.com/abanob0adel/Drag-And-Drop

Live Example: https://drag-and-drop-eight-psi.vercel.app/

Let's get started

Start improving your website performance today.

Let’s Contact