react-draggable icon indicating copy to clipboard operation
react-draggable copied to clipboard

How do you use percentages instead of pixels?

Open levelingup opened this issue 2 years ago • 1 comments

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.

levelingup avatar Sep 26 '21 03:09 levelingup

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

1alexvash avatar Oct 05 '21 13:10 1alexvash