react-draggable
react-draggable copied to clipboard
How to track the position of the Draggable component?
I want to track the (x, y) coordinates of the Draggable
component.
I can't use the position
prop like this, because then I cannot drag the component anymore:
const { posX, posY } = this.state;
return (
...
<Draggable position={{x: posX, y: posY}}>
<div style={{backgroundColor: "green", height: "30px", width: "30px"}}></div>
</Draggable>
...
);
I've looked a bit at the DraggableCore
API but I don't see how it could help me.
The only solution I found out yet is to set an onStop
handler to the Draggable
component like so:
handleOnStop(evt, data) {
const { x, y } = data;
this.setState({posX: x, posY: y});
}
Is there a simpler solution to bind directly the position coordinates in the parent state (posX, posY) to the props of the component?
same problem
I have a method I created to track the x, y via DOM const position = getTranslateValues(rndResizable);
/**
* Gets computed translate values */
export const getTranslateValues = (element: HTMLElement) => {
const style = window.getComputedStyle(element);
const matrix = style["transform"];
// No transform property. Simply return 0 values.
if (matrix === "none") {
return {
x: 0,
y: 0,
z: 0
};
}
// Can either be 2d or 3d transform
const matrixType = matrix.includes("3d") ? "3d" : "2d";
const matrixMatch = matrix ? matrix.match(/matrix.*\((.+)\)/) : null;
const matrixValues = matrixMatch ? matrixMatch[1].split(", ") : null;
if (!matrixValues) {
return {
x: 0,
y: 0,
z: 0
};
}
// 2d matrices have 6 values
// Last 2 values are X and Y.
// 2d matrices does not have Z value.
if (matrixType === "2d") {
return {
x: Number(matrixValues[4]),
y: Number(matrixValues[5]),
z: 0
};
}
// 3d matrices have 16 values
// The 13th, 14th, and 15th values are X, Y, and Z
if (matrixType === "3d") {
return {
x: Number(matrixValues[12]),
y: Number(matrixValues[13]),
z: Number(matrixValues[14])
};
}
return {
x: 0,
y: 0,
z: 0
};
};