I have a question. How to call a function when scroll down bottom of ScrollView in react native? Please help me. Thank so much!
4 Answers
It worked!
var windowHeight = Dimensions.get('window').height,
height = e.nativeEvent.contentSize.height,
offset = e.nativeEvent.contentOffset.y;
if( windowHeight + offset >= height ){
console.log('End Scroll')
}
2 Comments
animatedgif
Works great. Don't forget to
import { Dimensions } from 'react-native'John
where does the e variable come from?
You should pass a function to onScroll prop of ScrollView.
More info can be found here.
constructor(props){
super(props)
this._onScroll = this._onScroll.bind(this)
this.state = {
contentOffsetY: 0
}
}
_onScroll(e){
var contentOffset = e.nativeEvent.contentOffset.y;
this.state.contentOffsetY < contentOffset ? console.log("Scroll Down") : console.log("Scroll Up");
this.setState({contentOffsetY: contentOffset});
}
render(){
var items = ["1","2","3","4","5"];
return(
<ScrollView style={{flex: 1}} onScroll={this._onScroll}>
{items.map((item, i) => {
return (
<View key={i} style={{height: 200}}>
<Text>{item}</Text>
</View>
)
})}
</ScrollView>
)
}
3 Comments
jackmin
Thank you, Melih Mucuk. But how do i know i'm in bottom of ScrollView (end of ScrollView). Thanks you.
Melih Mucuk
there is an prop called "contentSize" in e.nativeEvent. Why dont you log it and see whats come from this? You should compare contentOffsetY and contentSizeY. For example (contentSizeY - contentOffsetY) < 100, there are only 100 pixels to end of the scrollview. @jackmin
jackmin
var windowHeight = Dimensions.get('window').height, height = e.nativeEvent.contentSize.height, offset = e.nativeEvent.contentOffset.y; if( windowHeight + offset >= height ){ console.log('End ScrollView') }
Kindly use these two methods of ScrollView full and final. Do not use ónScroll' because it will call many times on a single scroll.
onStartScrollList = () => {
this.setState({ isListScrolled: true });
console.log('onScrollList');
}
onStopScrollList = () => {
console.log('onStopScrollList');
this.setState({ isListScrolled: false });
}
Now check 'isListScrolled' in your 'loadMore' method.
Comments
If you want to capture the scrollToEnd event in a component, you can try the following method as an alternative
import { ScrollView, NativeScrollEvent } from 'react-native';
const someScrollAction = (event: NativeScrollEvent) => {
const layoutMeasurementHeight = +event.layoutMeasurement.height.toFixed(3);
const contentHeight = +event.contentSize.height.toFixed(3);
const contentOffset = +event.contentOffset.y.toFixed(3);
const totalHeight = +(layoutMeasurementHeight + contentOffset).toFixed(3);
if (totalHeight >= contentHeight) {
console.log('Scroll to end');
}
}
<ScrollView
onScroll={ (event) => someScrollAction(event.nativeEvent) }>
...
</ScrollView>