Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping a react native animated animation

Tags:

react-native

I am attempting to put the following animation in an infinite loop until a particular state occurs:

class MyModal extends Component {
    constructor() {
        super()
        this.springValue = new Animated.Value(0.3)
    }

    spring = () => {
        this.springValue.setValue(0.3)
        Animated.spring(
            this.springValue,
            {
                toValue: 1,
                friction: 1,
                tension: 1,
                duration:5000

            }
        ).start()
    }

    componentDidMount() {
        this.spring()
    }

    render() {
        return (
            <View>
                <Modal
                    animationType="none"
                    transparent={false}
                    visible={this.state.modalVisible}
                    onRequestClose={() => null}
                >
                    <View style={styles.backgroundStyle}>                       
                        <Animated.Image 
                            source={require("./my-awesome-image.png")} 
                            style={{ width: 143, height: 125, top: 100, transform: [{scale: this.springValue}]}}
                        />
                    </View>
                </Modal>
            </View>
        );
    }
}

Everything here works great, the animation completes once (as I'm not looping anywhere).

How do I keep my Animated.Image looping until I reach a particular state? I just want it infinite looping and the ability to either stop the animation or start another animation when I'm ready to.

like image 576
randombits Avatar asked Sep 12 '25 15:09

randombits


2 Answers

Store your animation in a variable you can access and just wrap your animation with Animated.loop(). Then you can freely use .start() and .stop() on that variable holding the animation as you please.

So something like this should do:

this.springAnimation = Animated.loop(
  Animated.spring(
    this.springValue,
    {
      toValue: 1,
      friction: 1,
      tension: 1,
      duration:5000
    }
  ).start()
)

You can find more information about that here:

https://facebook.github.io/react-native/docs/animated.html#loop

like image 160
ReyHaynes Avatar answered Sep 14 '25 05:09

ReyHaynes


Pass a callback to the start function to check whether to restart the animation. You could break it down to something like this:

    onSpringCompletion = () => {
      if (arbitraryCondition) {
        this.spring();
      }
    }

    spring = () => {
          this.springValue.setValue(0.3)
          Animated.spring(
              this.springValue,
              {
                  toValue: 1,
                  friction: 1,
                  tension: 1,
                  duration:5000

              }
          ).start(this.onSpringCompletion);
      }  
like image 45
Travis White Avatar answered Sep 14 '25 05:09

Travis White