Is it possible to get the current scroll position, or the current page of a
component in React Native?
So something like:
<
Use
<ScrollView
onMomentumScrollEnd={(event) => this.getscrollposition(event)}
scrollEventThrottle={16}>
Show Position
getscrollposition(e) {console.log('scroll y ', e.nativeEvent.contentOffset.y);}
If you wish to simply get the current position (e.g. when some button is pressed) rather than tracking it whenever the user scrolls, then invoking an onScroll
listener is going to cause performance issues. Currently the most performant way to simply get current scroll position is using react-native-invoke package. There is an example for this exact thing, but the package does multiple other things.
Read about it here. https://medium.com/@talkol/invoke-any-native-api-directly-from-pure-javascript-in-react-native-1fb6afcdf57d#.68ls1sopd
As for the page, I'm working on a higher order component that uses basically the above methods to do exactly this. It actually takes just a bit of time when you get down to the subtleties like initial layout and content changes. I won't claim to have done it 'correctly', but in some sense I'd consider the correct answer to use component that does this carefully and consistently.
See: react-native-paged-scroll-view. Would love feedback, even if it's that I've done it all wrong!
Brad Oyler's answer is correct. But you will only receive one event. If you need to get constant updates of the scroll position, you should set the scrollEventThrottle
prop, like so:
<ScrollView onScroll={this.handleScroll} scrollEventThrottle={16} >
<Text>
Be like water my friend …
</Text>
</ScrollView>
And the event handler:
handleScroll: function(event: Object) {
console.log(event.nativeEvent.contentOffset.y);
},
Be aware that you might run into performance issues. Adjust the throttle accordingly. 16 gives you the most updates. 0 only one.
I believe contentOffset
will give you an object containing the top-left scroll offset:
http://facebook.github.io/react-native/docs/scrollview.html#contentoffset
use of onScroll enters infinite loop. onMomentumScrollEnd or onScrollEndDrag can be used instead