Search code examples
reactjsreact-native

How to parse animated values in react native?


I want to parse the values shown in the <Animated.Text>.
I want only integer values not fractionated ones.

I'm getting this:
enter image description here

I want that:
enter image description here

I tried using:

<Animated.Text>{Number.parseInt(milliliters.ml)}</Animated.Text>

But I get errors, It doesn't work.

My example running online:
https://snack.expo.dev/@danilobatistaqueiroz/parsing_animated_values

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

My code:

import { Animated, Easing } from 'react-native';
import React from 'react';

export default function Milliliters() {

  const ML_LEVELS = [240,50,190];
  this.ml = React.useRef(new Animated.Value(ML_LEVELS[0])).current;

  this.ml_up_down = ()=>{
    Animated.sequence([
      Animated.timing(this.ml, {
        duration: 2000,
        toValue: ML_LEVELS[1],
        easing: Easing.bezier(.55,.5,.45,.5),
        useNativeDriver: false,
        delay: 0,
      }),
      Animated.timing(this.ml, {
        duration: 2000,
        toValue: ML_LEVELS[2],
        easing: Easing.ease,
        useNativeDriver: false,
        delay: 0,
      }),
    ]).start();
  }

}
import Milliliters from './milliliters';

import React from 'react';
import { Animated, Text } from 'react-native';

export default AddDrink = () => {

 const milliliters = React.useRef(new Milliliters()).current;

 React.useEffect(() => {
   milliliters.ml_up_down();
 });

 return (
   <Animated.Text>{milliliters.ml}</Animated.Text>
 );

}

Solution

  •  import React, { useRef, useState, useEffect } from "react";
     import { Animated, Easing, Text, View } from "react-native";
    
     export default function AddDrink() {
       const ML_LEVELS = [240, 50, 190];
       const ml = useRef(new Animated.Value(ML_LEVELS[0])).current;
    
       const [displayValue, setDisplayValue] = useState(ML_LEVELS[0]);
    
       useEffect(() => {
         // Update value of `displayValue` when `ml` changes
         const id = ml.addListener(({ value }) => {
           setDisplayValue(Math.round(value)); // Round the value to integer
         });
    
         return () => {
           ml.removeListener(id);
         };
       }, [ml]);
    
       const ml_up_down = () => {
         Animated.sequence([
           Animated.timing(ml, {
             duration: 2000,
             toValue: ML_LEVELS[1],
             easing: Easing.bezier(0.55, 0.5, 0.45, 0.5),
             useNativeDriver: false,
           }),
           Animated.timing(ml, {
             duration: 2000,
             toValue: ML_LEVELS[2],
             easing: Easing.ease,
             useNativeDriver: false,
           }),
         ]).start();
       };
    
       useEffect(() => {
         ml_up_down();
       }, []);
    
       return (
         <View>
           <Animated.Text>{displayValue}</Animated.Text>
         </View>
       );
          }