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

Calculate value of animation in useAnimaionStyle


I am working with react native reanimated 2

To make animations with opacity

This example works as well

  const width = useSharedValue(50);
  const animatedStyle = useAnimatedStyle(() => {
    return {
      opacity: width.value,
    };
  });
  return <Animated.View style={[styles.box, animatedStyle]} />;

But when I want to calculate any value that does not work

I get an error

const width = useSharedValue(50);
  const animatedStyle = useAnimatedStyle(() => {
    return {
      opacity: cond(greaterThan(width.value, 10), 1, 0),
    };
  });
  return <Animated.View style={[styles.box, animatedStyle]} />;

I get errors like that

cannot read property 'onFrame' on null

How can I calculate the value in 'useAmimationStyle'?

enter image description here


Solution

  • You are using reanimated v1 functions on the v2. You could do:

     const width = useSharedValue(50);
     const animatedStyle = useAnimatedStyle(() => {   
        return {
          opacity: width.value > 10 ? 1 :0
        };
      });
     return <Animated.View style={[styles.box, animatedStyle]} />;
    

    But the issue with this is that opacity wont really be animated; it would just instantaneously go to 1 or 0 when width.value got around 10. To get animation like opacity changes use interpolate:

    const width = useSharedValue(50);
      const animatedStyle = useAnimatedStyle(() => {
        return {
          width:width.value,
          opacity: interpolate(
            width.value,
            //input range
            [0, 10, 50],
            // output ramge
            [0, 0, 1]
          ),
        };
      });
     return <Animated.View style={[styles.box, animatedStyle]} />;
    

    Demo