Sometimes, we want to make React component/div draggable.
In this article, we’ll look at how to make React component/div draggable.
How to make React component/div draggable?
To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.
For instance, we write
import React, { useRef, useState, useEffect } from "react";
const quickAndDirtyStyle = {
width: "200px",
height: "200px",
background: "yellow",
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={quickAndDirtyStyle}
onMouseMove={onMouseMove}
onMouseDown={() => setPressed(true)}
onMouseUp={() => setPressed(false)}
>
<p>draggable</p>
</div>
);
};
export default DraggableComponent;
to check if the div is pressed with the onMouseDown and onMouseUp props.
If pressed is true, then we’re pressing on the div.
When the mouse is moving and pressed is true, then the setPosition function in onMouseMove is called.
In the useEffect callback, we watch the position value and set the transform style of the div as we drag the div.
The ref is set to the div with the ref prop.
Conclusion
To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.