4

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?

idolize
  • 6,455
  • 4
  • 24
  • 34

1 Answers1

8

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

import React from "react";
import { Pressable, Animated } 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/

AdamSusul
  • 207
  • 2
  • 8
  • Thanks, useful to-go animation that looks like touchableOpacity. However, it's unclear why the developers haven't added this functionality already to the component itself (as far as I know). – Dror Bar Dec 25 '22 at 14:13