9

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.

SudoPlz
  • 20,996
  • 12
  • 82
  • 123

1 Answers1

0

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()

Chris Dolphin
  • 1,578
  • 16
  • 28
  • 1
    Thanks for taking the time to answer, I haven't tested that solution (since I'm no longer on that project) but it looks like it would work. – SudoPlz Feb 07 '22 at 17:45