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?
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});
}
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.
If you use FlatList
instead of ScrollView
, by using ref you will get access to the scrollToIndex method.
https://reactnative.dev/docs/flatlist#scrolltoindex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With