React Native Animated, Complete Event
React NativeReact Native Problem Overview
What's the best practice to trigger an event when Animated.spring finishes?
Animated.spring(this.state.pan, {
toValue: 0
}).start()
I've searched quite a bit and haven't found a single way to do it. I could use addListener to check if the animation has reached it's end value or a timeout, but they both feel like ugly fixes to what should be super simple.
Does anyone know?
React Native Solutions
Solution 1 - React Native
Half an hour of googling later and i found this, can't believe they didn't document this better.
https://github.com/facebook/react-native/issues/3212
.start(callback)
Solution 2 - React Native
This will get fired at the start of the animation
.start(console.log("Start Animation")
Using an arrow function or function, done will get called at the END of the animation
.start(() => {console.log("Animation DONE")})
And finaly this is what it looks like in the context to of a function.
_play(){
Animated.timing(this.state.progress, {
toValue: 1,
duration: 5000,
easing: Easing.linear,
}).start(() => {console.log("Animation DONE")});
}
Hope that helps!
Solution 3 - React Native
Basically there these three approaches to do something when an animation finishes. First: you can use the callback passed into call(callback) method. Second: You can use stopAnimation which also accepts a callback Third: My preferred way,which consisting in placing a listener on the animated value,and do something based on the current value. For example, you can make a translation from 0 to 150 and based on a value you animate, say 'motion' and when motion reaches a value you can perform something.
let motion = Animated.Value(0);
motion.addListener(({value}) =>{
if(value>=10){
pos.stopAnimation((val)=>{console.log('stopped in '+val)});
}
});
More onhttps://www.youtube.com/channel/UCl5-W0A8tE3EucM7E_yS62A
Solution 4 - React Native
Now there are docs for this: https://reactnative.dev/docs/animated#working-with-animations
The updated answer should be:
.start(({finished}) => {
if (finished) {
console.log('animation ended!)
}
})