Search code examples
reactjsreact-nativereact-animated

How to force React Native Animated.timing to use only integers?


I need to force only integers in the range of values between the initial Animated.Value() and the toValue.

If there is another library for this type of animation, it's enough for my case.

this myValues = React.useRef(new Animated.Value(0)).current;

      Animated.timing(this.myValues, {
        duration: 2000,
        toValue: 500,
        easing: Easing.ease,
        useNativeDriver: false,
        delay: 0,
      }),

From 0 to 500 I want only integers. Is it possible?


Solution

  • import React, { useRef, useEffect, useState } from "react";
    import { View, Animated, Text } from "react-native";
    
    const App = () => {
    // Step 1: Create the Animated.Value
     const animatedValue = useRef(new Animated.Value(0)).current;
     const [displayValue, setDisplayValue] = useState(0);
    
      useEffect(() => {
        // Step 2: Define the animation
     Animated.timing(animatedValue, {
      toValue: 500,
      duration: 2000,
      easing: Easing.ease,
      useNativeDriver: false,
    }).start();
    
    // Step 3: Add a listener to round the value and update state
    const id = animatedValue.addListener(({ value }) => {
      setDisplayValue(Math.round(value));
    });
    
    // Cleanup listener on unmount
    return () => {
      animatedValue.removeListener(id);
    };
    }, [animatedValue]);
    
     return (
       <View>
        {/* Step 4: Use the rounded value in your render */}
        <Text>Value: {displayValue}</Text>
      </View>
      );
    };
    
     export default App;