skip to Main Content

Any advice on how to animate a number? I’m working on an app that will show the user’s current points on the home screen. When the screen is focused, I’d like the points to count up from 0 to their current total point value, over a duration of 900ms, rendering the animated value in a Text component.

I’ve tried a number of things with React Native’s Animated API as well as with different options for storing and referencing the state, and nothing has worked for me so far. Anyone done this before or have ideas to help me get unstuck? Thank you all!

2

Answers


  1. I’m new in react you can use React Spring for animating
    examples
    and maybe you need some thing like this
    example

    Login or Signup to reply.
  2. With ReAnimated 3 you can use a withTiming animation to set a shared value.

    Display the value using react-native-animateable-text

    import Animated, {useDerivedValue, useAnimatedProps} from 'react-native-reanimated';
    import AnimateableText from 'react-native-animateable-text';
    
    const Score = () => {
      // declare a shared value
      const points = useSharedValue<number>(0);
    
      // customize the format and display as string
      const animatedText = useDerivedValue(() => `Your score is ${points.value}`);
    
      // pass it as animated props
      const animatedProps = useAnimatedProps(() => ({
        text: animatedText.value;
      }));
    
      // stable counting function
      const countTo = useCallback((endValue: number) => {
        points.value = withTiming(endValue, {duration: 900});
      }, [points])
    
      useFocusEffect(useCallback(() => {  
        const init = () => {
    
          const endValue = 1000; // get your own endValue, this will count to 1000
    
          countTo(endValue);
        }
    
        init().catch(e => {
          if (e instanceof Error) {
            console.error(e.message);
          }
        });
    
        return () => {
          // start with points at 0, no animation
          points.value = 0;
        }
      },[countTo, points]);
    
      return (
        <View>
          <AnimateableText
          animatedProps={animatedProps}
          />
        </View>
      ) 
      
    }
    export default Score
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search