Search code examples
react-nativereact-native-reanimated-v2

Opacity fading animation not working with react-native-reanimated 2


I'm animating a bottom-sheet using react-native-reanimated(v2.2.0) also I need to change opacity of one view inside bottom-sheet with the animation.

Expected behavior.

Opacity of the view diereses when bottom-sheet came up. so the opacity of view should be 1 on bottom-sheet closed and opacity is 0 when bottom-sheet opens.

Problem

I'm using interpolate to get opacity value between 0 and 1 relatively with the bottom-sheet top position and using useAnimatedStyle to animate the opacity.

  const derived = useDerivedValue(() => {
    const opacity = interpolate(
      top.value,
      {
        inputRange: [top.value, 0],
        outputRange: [0, 1],
      },
      [top.value],
    );

    return opacity.value;
  });

  const style = useAnimatedStyle(() => {
    return {
      opacity: derived.value,
    };
  });

Then I'm using above style on my Animated.View

<PanGestureHandler onGestureEvent={gestureHandler}>
  <Animated.View style={[BottomSheetStyles, bottomSheetAnimatedStyles]}>
    <Animated.View                       //view i need to change opacity
      style={[MinPlayerStyles, style]}
      onPress={() => (top.value = withSpring(0, SPRING_CONFIG))}>
      <Text>Card</Text>
    </Animated.View>
  </Animated.View>
</PanGestureHandler>

Solution

  • I solve this problem by only using useAnimatedStyle and interpolate.

    Calculating opacity depending on bottom-sheet top value and giving it the range between 0 and 1 and returning opacity style.

      const minPlayerAnimatedStyles = useAnimatedStyle(() => {
        const opacity = interpolate(
          top.value,
          [0, top.value],
          [0, 1],
        );
    
        return {
          opacity,
        };
      });
    

    Now opacity changing on open bottom-sheet and close bottom-sheet but the opacity value not animating like a fading effect. What i want is to fade the opacity.

    Currently opacity sets to 1 as soon as the bottom-sheet starts. What i expected is to fade opacity.