Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HighLight / ScrollTo - ListView, ScrollView on React-Native

I'm playing a bit with react-native and I got stuck at a stage where I can't figure it out by myself. I have a list of items and I would like to scroll automatically to some item.

I know I could use the ScrollView and the contentOffset={{x:0,y:0}} and set and offset, however it would be a little bit more complicate because I would need to track the position of each item, I'm wondering if there is an easy way to do it, so I could sort of focus on specific row in ListView.

Is there such a thing available on the libs?

like image 201
Gabriel Lopes Avatar asked Jan 22 '16 23:01

Gabriel Lopes


3 Answers

The ScrollView does not provide a method to scroll to a specific list item - but it does provide the methods scrollTo({x, y, animated}).

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}).

In order to be able to access the ScrollView instance, you need to capture using the ref property callback:

<ScrollView ref={view => this._scrollView = view} />

And set the scroll position elsewhere with:

scrollToRow(itemIndex) {
  this._scrollView.scrollTo({y:itemIndex * ROW_HEIGHT});
}
like image 121
jevakallio Avatar answered Nov 18 '22 02:11

jevakallio


I have published react-native-scroll-into-view, a library which enable "scrollIntoView" feature for React Native ScrollView.

For other lists like SectionList you can still use item index like mentionned in other answers.

like image 24
Sebastien Lorber Avatar answered Nov 18 '22 02:11

Sebastien Lorber


If you use FlatList instead of ScrollView, by using ref you will get access to the scrollToIndex method.

https://reactnative.dev/docs/flatlist#scrolltoindex

like image 1
Adam Avatar answered Nov 18 '22 02:11

Adam