How To Use React Draggable In React Js

In this article, we learn how to use react draggable in react app.

First, we need to open our react app and install the dependency.

npm i react-draggable

Now we need to import Draggable from react-draggable.

import Draggable from "react-draggable";

Then take one useState and set the default value 0.

const [activeDrags,setActiveDrags] = useState(0)

For the draggable component, we take dragHandlers, and in that, we pass onStart and onStop properties with respective functions.

const onStart = () => setActiveDrags(activeDrags+1)
const onStop = () => setActiveDrags(activeDrags-1)

const dragHandlers = { onStart: onStart, onStop: onStop };

Now take the Draggable tag which is one imported from the react-draggable library and pass dragHandlers in that. Inside that take one div in that write whatever we want to show.

<Draggable {...dragHandlers}>
   <div className="box">I can be dragged anywhere</div>

Then only for horizontal and vertical drag do we need to pass axis props whose value is respective x and y in the Draggable tag.

<Draggable axis="x" {...dragHandlers}>
   <div className="box cursor-x"> I can only be dragged horizonally (x axis) </div>

<Draggable axis="y" {...dragHandlers}>
   <div className="box cursor-y"> I can only be dragged vertically (y axis) </div>

For not draggable component we need to pass onStart props and its value set false in Draggable tag.

<Draggable onStart={() => false}>
   <div className="box"> I don't want to be dragged </div>

Now write CSS for the set of the components.

* {
  box-sizing: border-box;

html, body {
  height: 100%;

body {
  color: #222;
  font-family: "Helvetica Neue", sans-serif;
  font-weight: 200;
  margin: 0 50px;

.cursor-y {
  cursor: ns-resize;

.cursor-x {
  cursor: ew-resize;

.box {
  background: #fff;
  border: 1px solid #999;
  border-radius: 3px;
  width: 180px;
  height: 180px;
  margin: 10px;
  padding: 10px;
  float: left;


Submit a Comment

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


Select Categories