Home > database >  How can I reset Animated.Value in React Native?
How can I reset Animated.Value in React Native?

Time:06-10

This is my code for animating components based on scrolling:

  const scrollY = useRef(new Animated.Value(0));
  const scrollYClamped = diffClamp(scrollY.current, 0, topBarHeight);

  const translateY = scrollYClamped.interpolate({
    inputRange: [0, topBarHeight],
    outputRange: [0, -topBarHeight]
  });
  console.log('scrollY', scrollY, scrollYClamped);

  useEffect(() => {
    console.log('in use effect');
  }, []);

  const handleScroll = Animated.event(
    [
      {
        nativeEvent: {
          contentOffset: { y: scrollY.current }
        }
      }
    ],
    {
      useNativeDriver: true
    }
  );

The thing which I want to achieve is reset the scrollY to the initial value whenever a method is called. Something like:

const resetValue = () => { scrollY = useRef(new Animated.Value(0)); }

Any idea how to achieve that?

CodePudding user response:

You can use the setValue method on the animated value. Something like the following should work for you:

scrollY.current.setValue(0);

You can read more about setValue here: https://reactnative.dev/docs/animatedvalue#setvalue

  • Related