Sometimes, we want to get the current scroll position of ScrollView in React Native.
In this article, we’ll look at how to get the current scroll position of ScrollView in React Native.
How to get the current scroll position of ScrollView in React Native?
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.
For instance, we write:
import * as React from 'react';
import { View, Text, ScrollView, Button } from 'react-native';
import { Card } from 'react-native-paper';
const a = Array(50)
.fill()
.map((_, i) => i);
const App = () => {
const scrollViewRef = React.useRef();
const [pos, setPos] = React.useState(0);
const [arr, setArr] = React.useState(a);
return (
<View style={{ flex: 1 }}>
<Text>pos: {pos}</Text>
<ScrollView
style={{ height: '200px' }}
onScroll={(e) => setPos(e.nativeEvent.contentOffset.y)}>
{arr.map((i) => (
<Text>{i}</Text>
))}
</ScrollView>
</View>
);
};
export default App;
to get the scroll position of the scroll view with e.nativeEvent.contentOffset.y
.
We call setPos
to set that as the value of pos
.
Now when we scroll, we see the pos
value change.
Conclusion
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.