Search code examples
react-native

React Native - How to add opacity feedback to Pressable component?


The new Pressable component is great; I like being able to access new events but, how do you add the opacity feedback the TouchableOpacity component has?


Solution

  • Given the answer of @Adams:

    Here is the code, which worked for me. You can customize it.

    import { useRef } from 'react';
    import { Pressable, Animated } from "react-native";
    
    const PressableOpacity = ({ children, ...props }) => {
      const animated = useRef(new Animated.Value(1)).current;
     
      const fadeIn = () => {
        Animated.timing(animated, {
          toValue: 0.1,
          duration: 100,
          useNativeDriver: true,
        }).start();
      };
      const fadeOut = () => {
        Animated.timing(animated, {
          toValue: 1,
          duration: 200,
          useNativeDriver: true,
        }).start();
      };
        
      return (
        <Pressable onPressIn={fadeIn} onPressOut={fadeOut} {...props}>
          <Animated.View style={{ opacity: animated }}>{children}</Animated.View>
        </Pressable>
      );
    };
        
    export default PressableOpacity;