Trying to Animate React Native Text Value

Jeremy picture Jeremy · Feb 10, 2017 · Viewed 15.3k times · Source

so basically im trying to get this render function to actually update the value in real time (as of now it just jumps to the final value upon completion of the animation)

I feel like because this library can animated values under the hood then there must be a way to display whats happening. Or is there some sort of content/value property I can feed in through style?

I've tried custom writing my own setInterval function, but I need it to line up better with other Animations' timing and I'd love access to RN's Easing library!

thanks!

Answer

Michael Cheng picture Michael Cheng · Feb 10, 2017

React Native has timers that you can use. For example, to do what you are trying to accomplish with setInterval:

state = {pleaseDisplayMe: 0}

componentDidMount() {
  setInterval(() => {
    this.setState({pleaseDisplayMe: this.state.pleaseDisplayMe + 1})
  }, 1000);
}

render() {
  return (
    <Text>{this.state.pleaseDisplayMe}</Text>
  )
}

However, if you are trying to instead trying to actually get the value from the animation, you should attach a listener to Animated and get the value from there as there is no way to synchronously read the value because it might be driven natively. A possibly very poor (I'm also new to React Native) example of this would be something like this:

state = {
  pleaseDisplayMe: new Animated.Value(0),
  value: 0,
}

triggerAnimation(){
  this.state.pleaseDisplayMe.addListener(({value}) => this.setState({value: value}));
  Animated.timing(
    this.state.pleaseDisplayMe,
    {toValue: 100,
    duration: 5000}
  ).start();
}

render() {
  return (
    <Text>{this.state.value}</Text>
  )
}