I'm trying to implement auto scroll in a ScrollView, but somehow can't figure the proper way of doing it, my idea, was something like, if I add an item and the contentSize overflows the ScrollView width I should scroll to the end, if I remove an item and the contentSize is smaller than the ScrollView width I should scroll to the start.
Here's what I have so far
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
ref={(scrollView) => {
this.scrollView = scrollView;
}}
onLayout={(e) => {
this.layoutWidth = e.nativeEvent.layout.width;
}}
onContentSizeChange={(contentWidth, contentHeight) => {
this.scrollView.scrollTo({
x: contentWidth > this.layoutWidth ? contentWidth + this.layoutWidth - width : 0,
y: 0,
animated: true,
});
}}>
{contacts.map((contact) => (
<SelectedContacsItem
contact={contact}
onRemoveContactPress={onRemoveContactPress}
key={contact.id}
/>
))}
</ScrollView>
This doesn't work for the remove items process, on the last items(when the content gets smaller than the view) it moves the content to random positions, I added the onScroll prop and watched the logs from there and seems that the contentOffSet is the issue because it has random values(sometimes negative values other times big numbers), not sure how to solve it.