Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reset a dragged component to its original position with react-draggable?

I try to implement a function in my app that allows the user to reset all the components that he dragged around to be reset to their original position.

I assume that this functionality exists in react-draggable because of this closed and released issue: "Allow reset of dragging position" (https://github.com/idanen/react-draggable/issues/7). However I did not find any hint in the documentation (https://www.npmjs.com/package/react-draggable).

There was one question with the same content in stackoverflow, but it has been removed (https://stackoverflow.com/questions/61593112/how-to-reset-to-default-position-react-draggable).

Thanks for your help :-)

like image 842
N008Y Avatar asked Oct 26 '25 07:10

N008Y


2 Answers

Note that this answer does not work.

None of these approaches worked for me, but tobi2424's post on issue 214 of the Draggable repo did. Here's a minimal proof-of-concept:

import React from "react";
import Draggable from "react-draggable";

const DragComponent = () => {
  // Updates the drag position parameter passed to Draggable
  const [dragPosition, setDragPosition] = React.useState(null);

  // Fires when the user stops dragging the element
  const choiceHandler = () => {
    setDragPosition({x: 0, y: 0});
  };

  return (
    <Draggable
      onStop={choiceHandler}
      position={dragPosition}
    >
      Drag me
    </Draggable>
  );
};

export default DragComponent;

Edit

The code above works intermittently but not particularly well. As far as I can work out, react-draggable stores data about the position of the dragged element somewhere outside of React, in order to preserve the position of the element between component refreshes. I was unable to determine how to reset the position of the element on command and none of the other example code solves the problem for me.

like image 85
Ross Angus Avatar answered Oct 29 '25 05:10

Ross Angus


I find resolve for this problem, and this simple.

<Draggable
   axis="both"
   handle=".handle"
   defaultPosition={{x: 0, y: 0}}
   position={{x: 0, y: 0}}
   scale={1}
}}>

You just need set up position prop, so after onStop he will back to {x: 0, y: 0}.

like image 42
Roman Shuvalov Avatar answered Oct 29 '25 06:10

Roman Shuvalov