React Native Scroll View “scroll control”

nitin varda
2 min readSep 26, 2021

--

Hey Guys, today we are going to see how we can control Scroll View component of react native .

github link: https://github.com/nitinvarda/scrollHandle

We create a new react-native project for this

npx react-native init scrollHandle

After succesfully creating the project create a new folder called src under root and a new file called Post.js under src project.

In Post.js we will create a mock of a post screen where we have a photo and description with a top nav bar with post title and back button.

While scrolling the the screen, after passing the image we will change style of top nav bar.

we will change background color of the navbar to gray and text color to black.

To achieve this we can use a prop called “onScroll” for ScrollView component .

On ScrollView component we have many event props for scroll like

  • onScroll
  • onScrollBeginStart
  • onScrollEndDrag
  • onScrollToTop

For more info you can check out the react-native official documentation of ScrollView component.

We are using onScroll Event to achieve above output.

onScroll will trigger an event when ever we scroll. that event has contentOffset object with values x and y. we are taking only “y” because we want to only check vertically for this scenario.

if you want to check horizontally you can use “x” value.

{ 
nativeEvent: {
contentInset: {bottom, left, right, top},
contentOffset: {x, y},
contentSize: {height, width},
layoutMeasurement: {height, width},
zoomScale
}
}

we have showTapNav value set to “false” by default with useState.

In changeOnScroll function we are checking if y value is greater than 250 or less . if it is greater we are settings showTapNav value to “true” else we are setting showTapNav value to “false”.

So according to this showTapNav value we are changing the style of top nav bar.

--

--