eballeste
eballeste

Reputation: 809

ReactNative [Flatlist] scrollToOffset, how do I figure out offset position of clicked row?

I want a row in a FlatList to scroll to the top of the screen whenever a user clicks on it. I am currently doing this by using the scrollToIndex method but the problem is that I have to animate the top margin (from 10 to 0) to get it flushed to the top of the screen. I also have an issue where if a user clicks on a row to expand the row, and a previous row was already expanded, the previous row will collapse causing the original scrollToIndex to animate to some position off the top of the screen.

My current two alternatives are to trigger an additional scrollToIndex once the previous row finishes contracting or use scrollToOffset to figure out where to scroll to based on good old math values. Is there a way to figure out row offset positions by index or some other value whenever it is clicked?

Thanks for any help anybody might be able to provide!

Upvotes: 3

Views: 22142

Answers (2)

yashodhank
yashodhank

Reputation: 61

You can use scrollToItem to achieve what you are trying to achieve

So suppose you have this FlatList component

<FlatList
        ref={(ref) => { this._flatList = ref; }}
        data = {dataSourche}
        renderItem = {(   info: {item:item, index:number}) => this._renderFlatListItem(info.item, info.index)}
        keyExtractor = {(item) => item.id}
        decelerationRate={0}
        snapToInterval={cardHeight}
        snapToAlignment={"start"} //Can also be 'center' or 'end'
        onMomentumScrollEnd = {(event) => this._onMomentumScrollEnd(event)}
        getItemLayout = {this.getItemLayout}/>

You will need to define a method getItemLayout that will tell the flatList 3 things

  1. length: In your case height of the card
  2. offset: this is distance from top of the list to current card usually we can set it as length * index of the card
  3. index of the card

so this is a sample getItemLayout which you can refer to

getItemLayout = (data, index) => (
        { length: 170, offset: 170 * index, index }
    );

Next will be your FlatList scrollToItem call

this._flatList.scrollToItem({
                animated:true, //can also be false
                item:item, 
                viewPosition:0 //this is the first position that is currently attached to the window
            })

Upvotes: 3

eballeste
eballeste

Reputation: 809

Instead of trying to figure out where to scroll to using the scrollToOffset method, I'm still using the scrollToIndex method and use the viewOffset parameter in order to calculate how much offset to add to the method: the difference between the expanded and collapsed heights of any other currently expanded item (if any) and subtracting the top margin of the clicked item.

Upvotes: 0

Related Questions