I have a scrollView element and I want to call different callback functions if user scrolls down or up
Asked
Active
Viewed 615 times
1 Answers
1
You can use the onScroll prop to get notified whenever the user scrolls.
In order to achieve your desired effect, you just need to store the position and if an update comes, check if the y position change with by a positive amount of pixel (down) or with a negative amount of pixels (up).
As a functional React component this can look like this:
function MyComponent() {
// we use a ref here in order to store the value between rendering without triggering an update (like useState would)
const scrollYRef = useRef(0)
return (
<ScrollView
onScroll={(event) => {
// 0 means the top of the screen, 100 would be scrolled 100px down
const currentYPosition = event.nativeEvent.contentOffset.y
const oldPosition = scrollYRef.current
if(oldPosition < currentYPosition) {
// we scrolled down
} else {
// we scrolled up
}
// save the current position for the next onScroll event
scrollYRef.current = currentYPosition
}}
....
/>
)
}

Maddis
- 577
- 1
- 6
- 19