How to know what direction is the user scrolling the ScrollView
. I want to show an action button based on the direction. I'm trying to find the direction with the following code:
import React, {Component} from 'react'
import { StyleSheet, Alert, ScrollView, View, Text } from 'react-native'
class ScrollDirection extends Component {
constructor(props){
super(props);
this.state = {
offset: 0
}
}
onScroll(event){
var currentOffset = event.nativeEvent.contentOffset.y;
var direction = currentOffset > this.offset ? 'down' : 'up';
this.state.offset = currentOffset;
Alert.alert(direction);
}
render() {
return (
<View style={styles.container}>
<ScrollView onScroll={this.onScroll}>
<View style={styles.scroller}>
<Text style={{fontSize:20,}}>ScrollDirection</Text>
</View>
</ScrollView>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
},
scroller: {
height: 5000,
},
});
export default ScrollDirection;
So on Scroll Up I want to alert Up and on Scroll Down alert Down. But I'm getting the following error:
What am I doing wrong? Or is there any better way to do it?
Many thanks!
Update 1:
Changed the state.offset to object, binded onScroll
and changed the onScroll function to setState:
constructor(props){
super(props);
this.state = {
offset: {}
}
this.onScroll = this.onScroll.bind(this)
}
onScroll(event){
var currentOffset = event.nativeEvent.contentOffset.y;
var direction = currentOffset > this.state.offset ? 'down' : 'up';
this.setState({
offset : currentOffset.y
}),
Alert.alert(direction);
}
But no matter which direction I scroll, I'm getting the Alert as up
. What am I missing?