ofundefined
ofundefined

Reputation: 3309

How can I get the value from an animated or interpolated value in React Native?

Short answer is: with addListener. Every animated variable has addListener() method accessible. Right? We should NOT access it from __getValue().


I was struggling to get the interpolated value (number) out of this const:

const interpolatedvalue = this.state.myanimvalue.interpolate({...})

I wanted to get the numeric value out of this interpolatedvalue. I was trying to use __getValue(), but I realized I should not do that.

Upvotes: 6

Views: 9039

Answers (3)

Jack Brian
Jack Brian

Reputation: 23

Attempting this in 2022, RN .70.5, adding an event listener for interpolatedValueY and then calling interpolatedValueY.__getValue() outside of the event listener should give you the updated value while useNativeDriver is set to true. Without the event listener, interpolatedValueY.__getValue() returns 0 no matter the actual animation value.

Upvotes: 0

ofundefined
ofundefined

Reputation: 3309

Updated

The right way of getting the value for an animated value is with a listener.

https://reactnative.dev/docs/0.5/animatedvalue#addlistener

Because the official docs say:

addListener(...) Adds an asynchronous listener to the value so you can observe updates from animations. This is useful because there is no way to synchronously read the value because it might be driven natively.

If the animation is driven by the native layer, we can not really get it synchronously. So let's always use addListener(value => {/*our logic to use value*/}).

Upvotes: 4

kreysix
kreysix

Reputation: 359

You can simply access the value as console.log(interpolatedValueY.__getValue())

Upvotes: 6

Related Questions