Open In App

How to add Draggable Components in Next.js ?

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn how we can add Draggable Components in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.

Approach:

To add our Draggable Components we are going to use the react-draggable package. The react-draggable package helps us to add draggable components anywhere in our app. So first, we will install the react-draggable package and then we will add a draggable component on our homepage.

Steps to create NextJS Application:

Step 1: create a new NextJs project using the below command

npx create-next-app gfg

Step 2: Install the react-draggable package using the below command

npm i react-draggable

Project Structure:

Adding the Draggable Component: After installing the react-draggable package we can easily add the Draggable Component in our app. For this example, we are going to add a draggable component to our homepage.

Add the below content in the index.js file:

CSS
/* index.css */
.draggable-container {
  text-align: center;
  padding: 20px;
}

.draggable-box {
  width: 200px;
  height: 100px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move; /* Change cursor to indicate draggable item */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  margin: 0 auto;
}
JavaScript
import Draggable from 'react-draggable';
import React from 'react';
import './Index.css'; 

export default function DraggableComponents() {
  return (
    <div className="draggable-container">
      <h3>GeeksforGeeks - Draggable Components</h3>
      <Draggable>
        <div className="draggable-box">We can move this text</div>
      </Draggable>
      <Draggable>
        <div className="draggable-box">Moe me!</div>
      </Draggable>
    </div>
  );
}

Explanation: In the above example first, we are importing our Draggable component from the installed package. After that, we are creating a new function named DraggableComponents and then we are using the Draggable Component that we just imported from the installed package. 

Steps to run the application: Run the below command in the terminal to run the app.

npm run dev

Output:

dragable



Next Article

Similar Reads