react-draggable
react-draggable copied to clipboard
How do you use percentages instead of pixels?
trafficstars
Say I want to create tags on an image, the tags are initially positioned by top/left css with percentages. However, when you use draggable on these tags, its only changing the transform css properties. But when you resize the browser, the images get resized too, causing issues to the tags because the transform css properties is only in pixels. If we're able to use percentages instead, it can be a better option.
You need to use controlled component via position prop
<Draggable onStart={onStart} onStop={onStop} position={position}></Draggable>
And then convert those units via onStart and onStop handlers
something like this
const onStart = (event: DraggableEvent, data: DraggableData) => {
const { node } = data;
setPosition({
x: (parseFloat(node.style.left) * fieldWidth) / 100,
y: (parseFloat(node.style.top) * fieldHeight) / 100,
});
node.style.left = "0";
node.style.top = "0";
};
const onStop = (event: DraggableEvent, data: DraggableData) => {
const { x, y, node } = data;
const newX = (x / fieldWidth) * 100;
const newY = (y / fieldHeight) * 100;
node.style.left = newX + "%";
node.style.top = newY + "%";
setPosition({
x: 0,
y: 0,
});
}
fieldWidth and fieldHeight is your container to calculate relative units from