Sometimes, we want to create draggable components in our React app.
In this article, we’ll look at how to create draggable components in our React app.
Make React Components Draggable
To create draggable components in our React app, we can make a component that handles the mousemnove
, mousedown
, and mouseup
events.
For instance, we can write:
import React, { useRef, useState, useEffect } from "react";
const style = {
width: "200px",
height: "200px",
background: "#FF9900",
color: "#FFFFFF",
display: "flex",
justifyContent: "center",
alignItems: "center"
};
const DraggableComponent = () => {
const [pressed, setPressed] = useState(false);
const [position, setPosition] = useState({ x: 0, y: 0 });
const ref = useRef();
useEffect(() => {
if (ref.current) {
ref.current.style.transform = `translate(${position.x}px, ${position.y}px)`;
}
}, [position]);
const onMouseMove = (event) => {
if (pressed) {
setPosition({
x: position.x + event.movementX,
y: position.y + event.movementY
});
}
};
return (
<div
ref={ref}
style={style}
onMouseMove={onMouseMove}
onMouseDown={() => setPressed(true)}
onMouseUp={() => setPressed(false)}
>
<p>{pressed ? "Dragging..." : "Press to drag"}</p>
</div>
);
};
export default function App() {
return (
<div className="App">
<DraggableComponent />
</div>
);
}
We have the style
object with some styles for our draggable component.
Then we define the DraggableComponent
which is a draggable component.
The pressed
state tracks when the component is clicked.
position
sets the div’s position.
In the useEffect
callback, we set the transform
CSS property to the position
that’s dragged.
Next, we add the onMouseMove
event handler to change the position
of the div when the mouse is pressed.
This is used to handle the mousemove
event.
To handle mouse down and mouse up, we set the pressed
state with setPressed
to true
and false
respectively so that the div can be moved when we press down the left mouse button.
Conclusion
To create draggable components in our React app, we can make a component that handles the mousemnove
, mousedown
, and mouseup
events.