Search code examples
reactjsresetreact-dnd

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 :-)


Solution

  • The referenced issue on the GitHub references a commit. After taking a look at the changes made in this commit, I found a resetState callback added to the useDraggable hook. In another place in the commit, I found a change to the test file which shows usage of the hook.

    function Consumer(props) {
        const {
          targetRef,
          handleRef,
          getTargetProps,
          resetState,
          delta,
          dragging
        } = useDraggable(props);
        const { style = defaultStyle } = props;
        return (
          <main
            className='container'
            ref={targetRef}
            data-testid='main'
            style={style}
            {...getTargetProps()}
          >
            {dragging && <span>Dragging to:</span>}
            <output>
              {delta.x}, {delta.y}
            </output>
            <button className='handle' ref={handleRef}>
              handle
            </button>
            <button onClick={resetState}>reset</button>
          </main>
        );
      }
    

    The hook returns a set of callbacks, including this callback, which can be used to reset the state of the draggable.