React-Draggable and React-Grid-Layout is are packages that let us create draggable elements in our React app.
In this article, we’ll look at how to create draggable elements with them.
To get started, we can install it by running:
npm install react-draggable
Then we can use it to create our draggable element by writing:
import React from "react";
import Draggable from "react-draggable";
export default function App() {
const handleStart = (e, data) => {
console.log(e, data);
};
const handleDrag = (e, data) => {
console.log(e, data);
};
const handleStop = (e, data) => {
console.log(e, data);
};
return (
<Draggable
axis="x"
handle=".handle"
defaultPosition={{ x: 0, y: 0 }}
position={null}
grid={[25, 25]}
scale={1}
onStart={handleStart}
onDrag={handleDrag}
onStop={handleStop}
>
<div>
<div className="handle">Drag from here</div>
<div>Drag me.</div>
</div>
</Draggable>
);
}
We use the Draggable
component from the package to let us drag items.
handle
is the class for the handle.
defaultPosition
is the x and y coordinate of the screen
axis
is the axis where we can drag the component.
x
limits the movement to the horizontal axis.
grid
is the x and y coordinate that dragging should snap to.
scale
is the scale of the canvas that we’re dragging the element on.
onStart
is called when the dragging starts.
onDrag
is a function that’s called while dragging.
onStop
is called when the dragging stops.
#web-development #javascript #react