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.
To get the current scroll position of ScrollView in React Native, we can set the onScroll prop of the ScrollView to a function that takes the scroll event object as an argument.
ScrollViews can be configured to allow paging through views using swiping gestures by using the pagingEnabled props. Swiping horizontally between views can also be implemented on Android using the ViewPager component. On iOS a ScrollView with a single item can be used to allow the user to zoom content.
If someone will run into this in the future: There isn't any 'built-in' property that will set ScrollView's direction to RTL at the moment. However That's what worked for me: set flexDirection: 'row-reverse' to ScrollView's style, which will order your items from right to left.
In the ScrollView, we can scroll the components in both direction vertically and horizontally. By default, the ScrollView container scrolls its components and views in vertical. To scroll its components in horizontal, it uses the props horizontal: true (default, horizontal: false).
I had problems with alexp's solution to accurately specify the direction when the difference between the old and the new offset was very small. So I filtered them out.
_onScroll = event => { const currentOffset = event.nativeEvent.contentOffset.y; const dif = currentOffset - (this.offset || 0); if (Math.abs(dif) < 3) { console.log('unclear'); } else if (dif < 0) { console.log('up'); } else { console.log('down'); } this.offset = currentOffset; };
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With