Search code examples
javascriptreactjsanimationreact-nativereact-animated

How can I interpolate a Animated value to result into a boolean or a string in react-native?


I happen to have an animation that goes from -1 to 1 and I want to translate those values into the following 2 strings:

'Previous' if the value is negative.

'Next' if the value is positive.

this.state.anim.interpolate({
    inputRange: [-1, 0, 1],
    outputRange: ['Previous','', 'Next'],
})

Q: How can I use the value that this.state.anim contains to decide wether we're going to the next screen or to the previous one.

More info:

this.state.anim receives it's values from a PanGesture and I'm using this.state.anim for many other things as well so it would be a shame not to use it here too.


Solution

  • For those looking for a react-native-reanimated v1.x solution, you can use the Math helpers to force an interpolated value into a boolean, or like in the OP's case, into strings:

    
    const interpolated = Animated.interpolate(
      value,
      {
        inputRange: [-1, 1],
        outputRange: [0, 1],
      },
    );
    
    const interpolatedAsInteger = Animated.round(interpolated);
    
    const boolean = Animated.cond(
      interpolatedAsInteger,
      new Animated.Value(true),
      new Animated.Value(false),
    );
    
    
    

    This example uses round() to force the interpolated value into a 0 or 1. Then cond() allows us to return an Animated node of whatever value we want. In this case I used true/false, but these could be strings like "Next" and "Previous".

    With more logic this approach can also handle the zero case, which should return an empty string.

    Docs for cond()