98
votes

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?

3

3 Answers

280
votes

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)
26
votes

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!

-1
votes

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 on👉https://www.youtube.com/channel/UCl5-W0A8tE3EucM7E_yS62A