Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect scroll end in React Native ScrollView, snap to page

Tags:

react-native

React Native ScrollView has a prop pagingEnabled . However, it assumes that the width of each page (or child component) in the ScrollView is equal to the width of the ScrollView.

How can we mend this to make it work correctly for pages that are smaller than the ScrollView?

Is it possible to detect when the user stops scrolling? Then we can easily write our own code to snap to the right page.

Edit: There are a few other ways to mend this by using props that are only available on iOS, so this is particularly a problem on Android.

like image 596
ArneHugo Avatar asked Jan 22 '17 16:01

ArneHugo


People also ask

What is contentContainerStyle?

contentContainerStyle: It is used to style the content of the ScrollView containers. contentInset: This property is used to inset the scroll view content by a specific amount. contentInsetAdjustmentBehavior: This property is used to identify how the safe area insets are used to modify the content area of the ScrollView ...

How do I scroll to a specific element in React Native?

If your list items are of equal height, you can use them to implement scrolling to a specific item by calling scrollTo({y:itemIndex * ROW_HEIGHT}) .


2 Answers

There are two different props you can set to React Native ScrollView which takes a callback to notify that scroll has ended. (They are now both documented.)


onScrollEndDrag function

Called as soon as the user lets go of the ScrollView (lifts the finger from the screen).

Working sample: https://rnplay.org/apps/Ufv6Cg (No longer available)


onMomentumScrollEnd function

Called when the ScrollView stops sliding (it will normally continue to slide a little bit after the user has lifted the finger from the screen).

Working sample: https://rnplay.org/apps/BPgG_g (No longer available)


Note: I could not find the methods in the API documentation for any React Native component, but they work as shown in the examples. I saw them used here in react-native-snap-carousel.

like image 80
ArneHugo Avatar answered Oct 12 '22 12:10

ArneHugo


Another option would be to use the snapToOffsets property which does exactly what you want.

This can be used for paginating through variously sized children that have lengths smaller than the scroll view.

like image 37
George Mavritsakis Avatar answered Oct 12 '22 14:10

George Mavritsakis