Tiago Correia
Tiago Correia

Reputation: 11

React-native ScrollView, auto scroll behaviour

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.

Upvotes: 0

Views: 2726

Answers (1)

Idan
Idan

Reputation: 4023

I do something like this before a week and i recommended to you (like me) to give up on ScrollView and map in this case

<FlatList
   ref={ref => this.flatListRef = ref}
   horizontal
   data={contact}
   extraData={this.state}
   keyExtractor={(item, index) => index}
   renderItem={({ item, index }) => <SelectedContacsItem
      contact={item}
      onRemoveContactPress={onRemoveContactPress}
      key={item.id}
      index={index}
    />}
/>

And the function onRemoveContactPress handle the scroll with the scrollToIndex property (don't forget to pass index)

onRemoveContactPress = (index) => {
    this.flatListRef.scrollToIndex({ animated: true, index: index });
}
  • if scrollToIndex don't scroll to the right index try to change index to something else ('play' with this)
  • in my case for example it's in RTL direction so it look like this: index: this.state.contact.length - index - 1

Upvotes: 1

Related Questions