Open In App

How to use react-draggable module in React JS ?

In React JS, the react-draggable module facilitates element dragging by utilizing CSS Transforms, enabling items to be draggable from any starting position. To implement this, the following approach can be employed in ReactJS.

Prerequisites:

Approach to use react-draggable:

We’ve showcased the utilization of the react-draggable module in our ReactJS application. By importing and incorporating the Draggable component into our main App component, any content within it becomes draggable across the screen using the mouse. As illustrated in the accompanying GIF, a div containing the text “This line can be moved now!” exemplifies this functionality.



Draggable Props:

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command:



npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Step 3: Installing the required module using the following command:

npm install react-draggable

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.6",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: Now write down the following code in the App.js file.




import React from 'react';
import Draggable from 'react-draggable';
import "./App.css"
import { Flex } from '@chakra-ui/react';
 
export default function App() {
    return (
        <>
            <div className='wrapper'>
                <h4>React-Draggable Module</h4>
                <div className='dragdiv'>
                    <Draggable>
                        <div>This line can be moved now!</div>
                    </Draggable>
                </div>
            </div>
        </>
    );
}




body {
    background-color: antiquewhite;
}
 
.wrapper {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: x-large;
    font-family:
    'Trebuchet MS', 'Lucida Sans Unicode',
    'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
 
.dragdiv {
    padding: 8rem;
    color: blueviolet;
    cursor: grabbing;
    font-size: medium;
    font-weight: 600;
    font-family:
        'Trebuchet MS', 'Lucida Sans Unicode',
        'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000

Output


Article Tags :