Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make draggable remember it's location in React Native

Tags:

react-native

I'm learning about the animation and panresponder apis in react native. Following Animated Drag and Drop with React Native and the source

I want to extend the example so that you can drag the circle without having to reset it. Currently the code animates the circle back to the center of the screen and relies on the panresponders dX/dY values.

my best guess is I have to change something in onPanResponderMove

  onPanResponderMove: Animated.event([null, {
    dx: this.state.pan.x,
    dy: this.state.pan.y,
  }]),

What do I need to change in the source so if I comment out the onPanResponderRelease logic the circle properly drags around the screen?

getTranslateTransform()?

like image 491
Harry Moreno Avatar asked Jan 20 '16 04:01

Harry Moreno


2 Answers

The logic in onPanResponderRelease is making it so that if the draggable is not in the dropzone when released, it is reset back to 0,0 (these are the lines causing it).

Removing that logic alone isn't all you should do though. You should set the offset and reset the value of this.state.pan in onPanResponderRelease. To do this you need to track the value.

In componentDidMount, add this:

this.currentPanValue = {x: 0, y: 0};
this.panListener = this.state.pan.addListener((value) => this.currentPanValue = value);

Then, in componentWillUnmount:

this.state.pan.removeListener(this.panListener);

Now that you have the current value, you just add this to the PanResponder:

onPanResponderRelease: (e, gestureState) => {
  this.state.pan.setOffset({x: this.currentPanValue.x, y: this.currentPanValue.y});
  this.state.pan.setValue({x: 0, y: 0});
},

It seems more complicated than it actually is. Basically you are just setting the offset from 0/0, then setting the value to 0/0 so that when you start moving it again after having released it before, it doesn't jump back to 0/0 before jumping back to where your finger is. It also makes sure you have its current position...which you will probably need at some point anyways.

like image 189
Dan Horrigan Avatar answered Oct 30 '22 09:10

Dan Horrigan


Another way would be to track current offset and keep adding it to the pan. So declare this in the constructor currentPanValue : {x: 0, y: 0},

And edit the onPanResponderRelease to the following :

onPanResponderRelease           : (e, gesture) => {
                this.state.currentPanValue.x += this.state.pan.x._value;
                this.state.currentPanValue.y += this.state.pan.y._value;

                this.state.pan.setOffset({x: this.state.currentPanValue.x, y: this.state.currentPanValue.y});
                this.state.pan.setValue({x: 0, y: 0});
            }

Incase if you want the final coordinates, you should get it with this.state.currentPanValue

like image 44
B K Avatar answered Oct 30 '22 09:10

B K