Search code examples
reactjsreact-nativeanimationgesturereact-animated

Animated event react native


I'm working with panResponder and I'm creating a simple view that follows the user's finger. I looked up and I found this example which works and I'm using it, but I can't wrap my head around it.

constructor(props){
this.state = {
  pan: new Animated.ValueXY()
}
this._val = { x: 0, y: 0 };
this.state.pan.addListener(value => (this._val = value));
// Initialize PanResponder with move handling
this.panResponder = PanResponder.create({
  onStartShouldSetPanResponder: (e, gesture) => true,
  onPanResponderMove: Animated.event([
    null,
    { dx: this.state.pan.x, dy: this.state.pan.y },
  ]),
  onPanResponderGrant: (e, gesture) => {
    // can't understand this part
    this.state.pan.setOffset({
      x: this._val.x,
      y: this._val.y,
    });
    this.state.pan.setValue({ x: 0, y: 0 });
 }
}

So, from what I can understand, when the user moves their finger, the onPanResponderMove is called with Animated.event which inside sets this.state.pan.x and this.state.pan.y to the delta x and y of the gesture, meaning that if the user has moved their finger 50 to bottom and 50 to right this.state.pan will be something like {x:50,y:50}.

Now why should I set an offset to the onPanResponderGrant? From what I see the offset will be 50 (previous value + 50 the dx taken from this._val.x that has been set with the listener when ANimated.event set the value on onPanResponderMove) so the view should move 100? And then we clear the this.state.pan values?

Can someone explain me better what's happening? Maybe with some easy numbers or a step by step example? Hope you can help me, it's been a whole day trying to figure it out. Thanks!


Solution

  • OnPanResponderGrant triggers first when you start moving the connected element. Using setOffset you 'save' previous value (this._val.x) in offset, which acts as a memory, or how much you have moved from the original location.

    Then you use setValue to set current (offseted) location as a new starting point.

    This way you have amount you have moved altogether saved in offset and value clean for handling just the current swiping amount (from latest press down to release).

    I hope this clears it up a bit, I had quite some issues with this as well.