Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native animated repeat infinity

Tags:

react-native

I have the following animation.

  componentWillMount(){
    this.animatedValue = new Animated.Value(300);
  }

  componentDidMount(){
    Animated.timing( this.animatedValue , {
      toValue: -100,
      duration: 3000,

    } ).start();
  }

  render() {
    const animatedStyle = { marginLeft: this.animatedValue, marginRight: - this.animatedValue };

    return (
      <View style={{flexDirection: 'row', height: 100,}}>
        <Animated.View style={[ animatedStyle,{backgroundColor: 'blue', width:100}]} />
      </View>
    );
  }

I would like to repeat endless times. Anyone have any suggestions?

like image 942
Alan Araujo Avatar asked Nov 26 '22 23:11

Alan Araujo


2 Answers

2019 solution:

Animated.loop(Animated.timing(this.animatedValue , {
    toValue: -100,
    duration: 3000,
})).start();
like image 88
Marcelo Avatar answered Feb 20 '23 17:02

Marcelo


Pass a callback to Animated.start() that resets the Animated value and starts the animation again. For example:

componentDidMount(){
  this.runAnimation();
}

runAnimation() {
  this.animatedValue.setValue(300);
  Animated.timing(this.animatedValue, {
    toValue: -100,
    duration: 3000,
  }).start(() => this.runAnimation());
}

If you need to stop the animation at any point, take a look at this question/answer.

like image 41
Michael Cheng Avatar answered Feb 20 '23 17:02

Michael Cheng