4
import React, { useRef, useState, useCallback } from 'react';
import { View, Animated } from 'react-native';
import { PanGestureHandler } from 'react-native-gesture-handler';


const InfoBox = ({ info }: Props) => {
  const [currenPos, setCurrentPos] = useState<number>(0);
  const translateY = useRef(new Animated.Value(0)).current;

  const onGestureEvent = useCallback(
    Animated.event(
      [
        {
          nativeEvent: {
            translationY: translateY,
          },
        },
      ],
      {
        useNativeDriver: true,
      },
    ),
    [],
  );

  const handleTransformStyle = {
    transform: [
      {
        translateY,
      },
      {
        translateX: -55,
      },
    ],
  };

  return (
    <View style={styles.container}>
      <PanGestureHandler
        onGestureEvent={onGestureEvent}
      >
        <Animated.View style={[styles.handleBar, handleTransformStyle]}>
          <View style={styles.separator} />
        </Animated.View>
      </PanGestureHandler>
    </View>
  );
};

export default InfoBox;

I have provided a very simple example of PanGestureHandler. On moving the box for the first time, it moves to a position and stays at that position. But, if I try to move it again, it starts from position zero instead of starting from the same position where I had left it.

Any help would be much appreciated.

EDIT

I have realized this occurs due to the offset getting reset.

shet_tayyy
  • 5,366
  • 11
  • 44
  • 82

1 Answers1

9

I have found a solution to this problem.

Add onHandlerStateChange to PanGestureHandler:

 <PanGestureHandler
    onGestureEvent={onPanGestureEvent}
    onHandlerStateChange={onHandlerStateChange}
 >
...
</PanGestureHandler>

Then, create a onHandlerStateChange function like so:

  const onHandlerStateChange = useCallback(() => {
    translateY.extractOffset();
  }, []);

translateY.extractOffset(); performed the magic. It sets the offset value. Phew!

shet_tayyy
  • 5,366
  • 11
  • 44
  • 82
  • Is it possible to add some sort of checks in the onGestureFunciton? Or can we only use the event directly? See this please https://stackoverflow.com/questions/64330969/stop-dragging-after-a-limit-has-reached –  Oct 13 '20 at 08:55
  • Hi, I have the same problem with PinchGestureHandler. But I try with some function such as scale.extractOffset() or scale.flattenOffset, there is no affect. Does you have any suggestion for this problem? – Quang Khải Đàm Oct 14 '20 at 09:58
  • Unfortunately, the documentation is very confusing. You might have to really implement, test and try to find a solution. That's what I had to do – shet_tayyy Oct 16 '20 at 19:03