React-native animated.event custom onScroll listener

Viewed 21160

In official react-native documentation there is a section about Animated.event method. As example they use following code:

onScroll={Animated.event(
   // scrollX = e.nativeEvent.contentOffset.x
   [{ nativeEvent: {
        contentOffset: {
          x: scrollX
        }
      }
    }]
 )}

I would like to map correct values to Animated.event method and I would also like to map onScroll callback parameters to my own callback. Basically I would like to do something like this:

onScroll={(event) => {
  myOwnCallback(event.nativeEvent.contentOffset.x)
  Animated.event(
    // scrollX = e.nativeEvent.contentOffset.x
    [{nativeEvent: {
        contentOffset: {
          x: scrollX
        }
      }
    }]
  )
}}

Could you please explain how to do that?

3 Answers

Write handler function like:

    handleScroll = (e) => {
        console.log(e.nativeEvent.contentOffset.y);
    }

and you can add listener like this:

    Animated.event(
       [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
       { listener: (event) => this.handleScroll(event) }
    )

Couldn't get Michal's solution to work for me. Ended up going with this

onScroll={({ nativeEvent }) => {
               animatedY.setValue(nativeEvent.contentOffset.y);
               // other actions to be performed on scroll
         }}
Related