Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Animated Value in React Native Render Text Component

I can not display the Value of Animated on the Render and returns this error.

Invariant Violation: Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead.

Of course, I see the Value in the console

constructor(props) {
    super(props);

    this.state={
       progress:0
    }

    this.animatedValue = new Animated.Value(0);

    this.animatedValue.addListener((progress) => {
        this.setState({progress})
    });
}

componentDidMount() {
    this.animate()
}

animate() {
    this.animatedValue.setValue(0);
    Animated.timing(
        this.animatedValue,
        {
            toValue: 1,
            duration: 15000,
            easing: Easing.linear
        }
    ).start()
}

render() {
    return(
        <View>
            <Text> {this.state.progress} </Text>
        </View>
    );

}
like image 560
Mahdi Bashirpour Avatar asked Jul 03 '18 18:07

Mahdi Bashirpour


2 Answers

The function given to addListener will be called with an object with a value key as argument, so instead of setting progress with the entire object, use the value instead:

this.animatedValue.addListener((progress) => {
  this.setState({ progress: progress.value });
});
like image 68
Tholle Avatar answered Sep 30 '22 05:09

Tholle


Tholle solution works fine if the animated value doesn't change that much, because it will cause a component re-render(as mentioned by @saeedZhiany in his comment) each time the value changes and that can lead to performance issues.

The better solution for these cases is to use ._value property of animatedValue, something like this:

 <Text>
    {Math.round(this.animatedValue._value)}
 </Text>

This way you get the real value at anytime without updating the component state. Thus avoiding performance issues.

like image 27
ismnoiet Avatar answered Sep 30 '22 04:09

ismnoiet