Search code examples
listviewscrollviewreact-native

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?


Solution

  • 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});
    }