Reputation: 809
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
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
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
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