Reputation: 5755
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.
Upvotes: 5
Views: 3021
Reputation: 5755
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!
Upvotes: 10