6

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>
    );

}
0

2 Answers 2

9

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 });
});
Sign up to request clarification or add additional context in comments.

3 Comments

This will causes state of component changes, and so Re-rendering!, am I right? if yes, any better idea exists?
A good way to avoid unnecessary re-renders would be to depend upon a condition before calling setState, e.g., if (Math.round(progress.value) !== this.state.progress)
Another way of avoiding too many rerenders is using a throttle
1

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.

1 Comment

Note: If useNativeDriver: true this will always return 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.