react-nativeanimationexporeact-native-reanimated-v2

Smooth transitions with the new "Pressable" component?


I've been using TouchableOpacity for ease of use in my react native project, but I'm interested in trying the new Pressable component instead - given how flexible its API is.

However, while the new Pressable API gives me the ability to change things like style props based on a pressed state easily, there is no smooth/animated transition like there is with the opacity in TouchableOpacity! Instead, the transition happens instantly when pressed/unpressed.

What is the best way to use Pressable but also make a nice, smooth transition between the pressed/unpressed style changes? I assume I'll have to use the Animated API in some way? Does anyone have an example of this?


Solution

  • You can use Animated Api Here is a example of Animated Api:

    import { Pressable, Animated, View } from "react-native";
    
    const Component = () => {
      const animated = new Animated.Value(1);
    
      const fadeIn = () => {
        Animated.timing(animated, {
          toValue: 0.4,
          duration: 100,
          useNativeDriver: true,
        }).start();
      };
      const fadeOut = () => {
        Animated.timing(animated, {
          toValue: 1,
          duration: 200,
          useNativeDriver: true,
        }).start();
      };
    
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Pressable onPressIn={fadeIn} onPressOut={fadeOut}>
            <Animated.View
              style={{
                opacity: animated,
                backgroundColor: "red",
                padding: 50,
                borderRadius: 20,
              }}
            >
              <Text>Text</Text>
            </Animated.View>
          </Pressable>
        </View>
      );
    };
    

    Animated Api docs: https://reactnative.dev/docs/animated

    Also i recommend to check out reanimated library to create animation with native performance

    https://docs.swmansion.com/react-native-reanimated/