Search code examples
react-nativeinterpolationreact-animated

Unable to interpolate color while moving object


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

const ANIMATION_DURATION = 250;

class Ball extends Component {
  
  componentWillMount() {
    this.position = new Animated.ValueXY(0,0);
    this.borderC = new Animated.Value(0);
    
    Animated.parallel([
      Animated.timing(this.position, {
        toValue: { x: 200, y: 500 },
        duration: ANIMATION_DURATION
      }),
      Animated.timing(this.borderC, {
        toValue: 1,
        duration: ANIMATION_DURATION,
      })
    ]).start();
  }
  
  
  render() {
    const styl = {
      ball: {
        height: 60,
        width: 60,
        borderRadius: 30,
        borderWidth: 30,
        borderColor: this.borderC.interpolate({
          inputRange: [0, 1],
          outputRange: ['green', 'yellow'],
        })
      }
    }
  
    return (
      <Animated.View style={this.position.getLayout()}>
        <View style={styl.ball}/>
      </Animated.View>
    );
  }
}



export default Ball

I have a simple component which trying to move the ball from one point to another point, and at the same time changing the color from green to yellow. There is no error being thrown and the ball does move. However I couldn't figure out which part could've gone wrong.

I've implemented Animated.parallel in order to have both the animation running together and implemented interpolate at borderColor with inputRange of 1 and 0 as well as outputRange

This is the Expo snack for you to play around


Solution

  • Your second View component that needs the border-color transition should be a Animated.View too.

    Sample

      render() {
        const style = {
          ball: {
            height: 60,
            width: 60,
            borderRadius: 30,
            borderWidth: 30,
            borderColor: this.borderC.interpolate({
              inputRange: [0, 1],
              outputRange: ['green', 'yellow'],
            })
          }
        }
    
        return (
          <Animated.View style={this.position.getLayout()}>
            <Animated.View style={styl.ball}/>
          </Animated.View>
        );
      }