Author - StudySection Post Views - 702 views
Draggable

Make React Elements Draggable

React is an open-source, front-end javascript library to build web applications, It is used to build single-page applications. It allows developers to create reusable components. It is led by Facebook and individuals in the community.

User experience and interactivity are becoming more important in modern apps. Many applications like Wix, Jira are using the drag and drop feature in their app. So, it is sometimes good to add drag and drop elements in your app. We are going to create a react application in which a user can drag a box around the screen.

Step 1: Install npm package
After creating your app with create-react-app draggable-demo , run the below command in your project:
npm install react-draggable

Step 2: Create a style object
Create a style object on the top of the file App.js above App component and below imports. This will shape the element that we are going to make draggable.
const styles = {
draggableContainer:{
backgroundColor: '#eb596e',
padding:'65px 35px',
borderRadius:'100px'
}
}

Step 3: Add a draggable component in your App.js.
In App.js, you need to import the Draggable component from the package you have installed using the above command.
import Draggable from 'react-draggable';

Now wrap the element with Draggable that you want to drag as shown below, note that the “handle” prop value should be the className of the element you want to make draggable.
<Draggable
handle=".handle">
<div>
<div style={styles.draggableContainer} className="handle">Drag me</div>
</div>
</Draggable>

The <Draggable> element wraps an element and extends it with new event handlers and styles. It does not create a wrapper element inside the Document Object Model(DOM). You can use new event handlers according to your requirements.

Here is the complete code of App.js
import './App.css';
import Draggable from 'react-draggable';
const styles = {
draggableContainer:{
backgroundColor: '#eb596e',
padding:'65px 35px',
borderRadius:'100px'
}
}
function App() {
return (
<div className="App">
<header className="App-header">
<Draggable
handle=".handle">
<div>
<div style={styles.draggableContainer} className="handle">Drag me</div>
</div>
</Draggable>
</header>
</div>
);
}
export default App;

Step 4: Now run the below command to start your app:
npm start

Draggable

For more information about the Draggable component, you can check this github repository.

Get certification for your knowledge in the fundamentals of Computer functioning by clearing the Computer Certification Exam conducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri