Skip to content

Instantly share code, notes, and snippets.

@dilipsuthar97
Created July 28, 2021 15:53
Show Gist options
  • Save dilipsuthar97/56e6d483dc41af5f681eefd989c2163e to your computer and use it in GitHub Desktop.
Save dilipsuthar97/56e6d483dc41af5f681eefd989c2163e to your computer and use it in GitHub Desktop.
import React from 'react';
import { Animated } from 'react-native';
import {
TapGestureHandler,
LongPressGestureHandler,
State,
} from 'react-native-gesture-handler';
export default ({
children,
disabled = false,
onPress,
onLongPress,
activeScale = 0.95,
springConfig = {
damping: 20,
mass: 1,
stiffness: 350,
},
style,
}) => {
const scale = React.useRef(new Animated.Value(1)).current;
const sz = {
transform: [{ scale: scale }],
};
const animateIn = () => {
Animated.spring(scale, {
toValue: activeScale,
useNativeDriver: true,
...springConfig,
}).start();
};
const animateOut = () => {
Animated.spring(scale, {
toValue: 1,
useNativeDriver: true,
...springConfig,
}).start();
};
const handleLongTapGestureState = ({ nativeEvent }) => {
if (disabled) return;
const { state } = nativeEvent;
if (state == State.ACTIVE) {
onLongPress && onLongPress();
}
};
const handleTapGestureState = ({ nativeEvent }) => {
if (disabled) return;
const { state } = nativeEvent;
if (state == State.BEGAN) {
animateIn();
}
if (state == State.END) {
onPress && onPress();
animateOut();
}
if (
state === State.UNDETERMINED ||
state === State.FAILED ||
state === State.CANCELLED
) {
animateOut();
}
};
return (
<LongPressGestureHandler
enabled={onLongPress ? true : false}
onHandlerStateChange={handleLongTapGestureState}
minDurationMs={600}>
<TapGestureHandler
shouldCancelWhenOutside={true}
onHandlerStateChange={handleTapGestureState}>
<Animated.View style={[style, sz]}>{children}</Animated.View>
</TapGestureHandler>
</LongPressGestureHandler>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment