React.js Drag Components and Elements in Website Using react-draggable Library Full Tutorial with Example

React.js Drag Components and Elements in Website Using react-draggable Library Full Tutorial with Example

 

Welcome folks today in this blog post we will be talking about react-draggable library by which we can drag components and elements in website. We will be looking at all examples of this library. All the source code of examples are given below.

 

 

Get Started

 

 

In order to get started you need to install this npm package from node package manager

 

npm i react-draggable

 

After executing this command the library will be installed and now we can use it

 

A simple component for making elements draggable.

 

<Draggable>
  <div>I can now be moved around!</div>
</Draggable>

 

Version Compatibility
4.x React 16.3+
3.x React 15-16
2.x React 0.14 – 15
1.x React 0.13 – 0.14
0.x React 0.10 – 0.13

 

 

Now inside your react.js project make a app.js file and copy paste the following code

See also  Build a React.js RGBA to HEX Color Converter Web App in Javascript Full Project For Beginners

 

 

app.js

 

 

import React from 'react';
import ReactDOM from 'react-dom';
import Draggable from 'react-draggable';

export default function App() {
  return (
    <Draggable
      axis="x"
      handle=".handle"
      defaultPosition={{x: 0, y: 0}}
      position={null}
      grid={[25, 25]}
      scale={1}
      onStart={this.handleStart}
      onDrag={this.handleDrag}
      onStop={this.handleStop}>
      <div>
        <div className="handle">Drag from here</div>
        <div>This readme is really dragging on...</div>
      </div>
    </Draggable>
  );
}

 

 

 

So here if you execute this and open it now you can drag the element in only x axis direction because we have provided the value x inside axis parameter

 

 

 

 

 

DraggableCore API

 

 

<DraggableCore> takes a limited subset of options:

 

 

{
  allowAnyClick: boolean,
  cancel: string,
  disabled: boolean,
  enableUserSelectHack: boolean,
  offsetParent: HTMLElement,
  grid: [number, number],
  handle: string,
  onStart: DraggableEventHandler,
  onDrag: DraggableEventHandler,
  onStop: DraggableEventHandler,
  onMouseDown: (e: MouseEvent) => void,
  scale: number
}

 

 

Leave a Reply