18

I have inverted vertical FlatList in my chat app, which shows newest message in bottom and oldest message in top (likes all other chat applications)
The problem is when I want to add new messages to bottom of my list, FlatList automatically jump to bottom-end of the list!
All I need is to prevent scrolling in this situation

Here is my FlatList:

<FlatList
  inverted
  style={{flex: 1}}
  data={this.state.data}
  keyExtractor={(item, index) => item.id}
  renderItem={this.renderItem}
/>

And here is the code to add newest messages to list

const data = [ ...newMessages, ...this.state.data ];
this.setState({ data });
SiSa
  • 2,594
  • 1
  • 15
  • 33

3 Answers3

0

Your case look simple but you are adding new message at top then reverse it to bottom last position using inverted flag

Could remove inverted flag and add new item at last simply const data = [...this.state.data, ...newMessages];

<FlatList
  style={{flex: 1}}
  data={this.state.data}
  keyExtractor={(item, index) => item.id}
  renderItem={this.renderItem}
/>

const data = [...this.state.data, ...newMessages];
this.setState({ data });

I hope this will work

Prabhunath Yadav
  • 185
  • 1
  • 14
  • 1
    I need to add new items in both side of `FlatList` as I mention in my question: **which shows newest message in bottom and oldest message in top (likes all other chat applications)** – SiSa Nov 23 '19 at 08:35
0

Put this in the view

<FlatList
  data={this.state.data}
      ref={ref => {
        this.flatListRef = ref;
      }}
      initialScrollIndex={0}
      keyExtractor={item => item.id}
      extraData={this.state.refresh}
      renderItem={({item, index}) => {
        // animation={animation}
        return (
          <ListItem
            inAnimation={inAnimation}
            outAnimation={outAnimation}
            duration={duration}
            easing={easing}
            isDeleted={item._isDeleted}
            id={item.id}
            item={item}
          />
        );
      }}
    `/>`

Run this in a function

this.flatListRef.scrollToIndex({
       animated: true,
       index: nextProps.indexScroll})

  });
-1

You should use a workaround to achieve this. If you check the documentation for FlatList (which extends the props of ScrollView), you'll see that all you need to do is set the scrollEnabled prop to false to disable scrolling. How and where you choose to do this will be up to you since you didn't really post a lot of code. A simple way to handle this would be to use state:

<FlatList
  ...
  scrollEnabled={this.state.scrollEnabled}
/>

In your case you could change the state when the new data is being loaded and change it back when it is rendered.

There is an open issue on Github about this case.

Jurrian
  • 850
  • 6
  • 20
  • 3
    Thanks for your attention, but this is not work and `FlatList` still scrolls down automatically after adding new items even if `scrollEnabled` sets to `false` – SiSa Nov 23 '19 at 08:31