Finding out scroll direction in react-native listview/scrollview

Secret picture Secret · Apr 20, 2016 · Viewed 28.8k times · Source

Is there a way to find out the scroll direction of react-native's listview/scrollview components?

Native iOS components seem to be able to do it by calculating the offset from scrollViewWillBeginDragging and scrollViewDidScroll, but there seems to be no bindings for these.

Answer

alexp picture alexp · Apr 23, 2016

You can use the onScroll event of a ScrollView and check the contentOffset in the event callback:

https://rnplay.org/apps/FltwOg

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  ScrollView,
  Text,
  View,
} = React;

var SampleApp = React.createClass({
  offset: 0,
  onScroll: function(event) {
    var currentOffset = event.nativeEvent.contentOffset.y;
        var direction = currentOffset > this.offset ? 'down' : 'up';
    this.offset = currentOffset;
    console.log(direction);
  },
  render: function() {
    return (
      <View style={styles.container}>
        <ScrollView style={styles.scroller} onScroll={this.onScroll}>
          <Text>Scrollable content here</Text>
        </ScrollView>
      </View>
    )
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
  },
  scroller: {
    height: 5000,
  },
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);