Skip to content

Instantly share code, notes, and snippets.

@statico
Created September 18, 2023 02:07
Show Gist options
  • Save statico/c9f3544111f31ed249ca5922555a650f to your computer and use it in GitHub Desktop.
Save statico/c9f3544111f31ed249ca5922555a650f to your computer and use it in GitHub Desktop.
Simple Pressable with Opacity component for React Native
/**
* Why?
*
* Pressable is the newer and superior component in React Native for buttons.
* It has a built in affordance for near-misses and, most importantly, it
* doesn't respond or show an animation while the user is dragging.
*
* However, Pressable doesn't have any feedback, like TouchableOpacity. This
* simple component adds the animation you want *when* the user is actually
* committed a press. This is how, for example, the official Facebook app works.
*
* @see demo at https://snack.expo.dev/@pickleheadsian/button-tests-in-scrollview?platform=web
*/
const PressableWithAnimation = React.memo((props) => {
const animated = useRef(new Animated.Value(1)).current;
const handlePress = () => {
animated.setValue(0.4);
Animated.timing(animated, {
toValue: 1,
duration: 400,
useNativeDriver: true,
}).start()
if (props.onPress) props.onPress();
};
return (
<Pressable onPress={handlePress}>
<Animated.View style={[styles.button, { opacity: animated }]}>
{props.children}
</Animated.View>
</Pressable>
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment