Search code examples
javascriptreact-nativereact-animated

Undefined is not an object animated.interpolate react native


I am looking at how to animate colors in react native and followed this tutorial https://codedaily.io/screencasts/8/Animate-Colors-with-React-Native-Interpolate

All I have done is first run react-native init then replace the code in my App.js with this

import { StyleSheet, View, Text, Animated } from 'react-native';
import React, { Component } from 'react';

export default class App extends Component {

componentDidMount() {
  this.animatedValue = new Animated.Value(0);
}

componentDidMount() {
 Animated.timing(this.animatedValue, {
  toValue: 150,
  duration: 1500
}).start();
}

    render() {
    const interpolateColor = this.animatedValue.interpolate({
      inputRange: [0, 150],
      outputRange: ['rgb(0,0,0)', 'rga(51,250,170)']
    });

    const animatedStyle = {
      backgroundColor: interpolateColor
    }
    return (
      <Animated.View style={[{ width: 50, height: 50 }, animatedStyle]} />
    );
}
}

And then run react-native run-android

And now I keep getting TypeError:undefined is not an object(evaluating 'this.animatedValue.interpolate')


Solution

  • The componentDidMount lifecycle method only runs after the first render. Therefore this.animatedValue will be undefined when the component first mounts.

    You can declare the animated value as an instance property on the component, so that it will be available from when the component is first created.

    export default class App extends Component {
      animatedValue = new Animated.Value(0)
    
      //...
    }
    

    Additionally, you can't define multiple componentDidMount methods as you have here.