12

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?

Michal
  • 4,952
  • 8
  • 30
  • 63

3 Answers3

56

When you look at the source code:

/**
   * Takes an array of mappings and extracts values from each arg accordingly,
   * then calls `setValue` on the mapped outputs.  e.g.
   *
   *```javascript
   *  onScroll={Animated.event(
   *    [{nativeEvent: {contentOffset: {x: this._scrollX}}}]
   *    {listener},          // Optional async listener
   *  )
   *  ...
   *  onPanResponderMove: Animated.event([
   *    null,                // raw event arg ignored
   *    {dx: this._panX},    // gestureState arg
   *  ]),
   *```
   *
   * Config is an object that may have the following options:
   *
   *   - `listener`: Optional async listener.
   *   - `useNativeDriver`: Uses the native driver when true. Default false.
   */
  event,

This is how I made it work:

onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
  {
    useNativeDriver: true,
    listener: event => {
      const offsetY = event.nativeEvent.contentOffset.y
      // do something special
    },
  },
)}
Michal
  • 4,952
  • 8
  • 30
  • 63
  • 9
    How do you add an function as a listener here? I tried binding it in there but it doesn't seem to fire. Any further explanation about this? – Pim Aug 24 '19 at 20:47
3

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
         }}
Cels
  • 1,212
  • 18
  • 25
2

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) }
    )
hannojg
  • 983
  • 8
  • 28
Hrishi
  • 1,210
  • 1
  • 13
  • 25