I'm facing an issue in which I need to change header text position from left to centre when user begin scroll and back to left if user scroll to top. But I unable to find solution for. I'm using scrollview which have a lot of content inside it. Can anyone tell me how to do that?
Asked
Active
Viewed 1,869 times
1
-
You can use `onScroll` in your ScrollView. It provides this props `{nativeEvent: {contentInset: {bottom, left, right, top},contentOffset: {x, y},contentSize: {height, width},layoutMeasurement: {height, width},zoomScale}}`. You can use contentOffset for your purpose. – Rohit Aggarwal Feb 15 '22 at 12:01
2 Answers
1
You can find a solution here :
<ScrollView
onScroll={({nativeEvent})=>{
if(isCloseToTop(nativeEvent)){
//do something
}
if(isCloseToBottom(nativeEvent)){
//do something
}
}}
>
...contents
</ScrollView>
isCloseToBottom({layoutMeasurement, contentOffset, contentSize}){
return layoutMeasurement.height + contentOffset.y >= contentSize.height - 20;
}
ifCloseToTop({layoutMeasurement, contentOffset, contentSize}){
return contentOffset.y == 0;
}

mohamed shameem
- 61
- 1
- 4
1
Try this way
import React, { useState, useEffect } from "react";
function Example() {
const [scrollPosition, setScrollPosition] = useState(-1);
useEffect(() => {
// console.log("scrollPosition: ", scrollPosition);
if (scrollPosition === 0) {
// condition is true when scroll on top
}
}, [scrollPosition]);
const getscrollposition = (e) => {
const y = e.nativeEvent.contentOffset.y;
setScrollPosition(y);
};
return (
<ScrollView
onMomentumScrollEnd={getscrollposition}
scrollEventThrottle={16}
>
.....
</ScrollView>
);
}

Nooruddin Lakhani
- 7,507
- 2
- 19
- 39