Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native flatlist initial scroll to bottom

Tags:

I am trying to create a chat in React native using a <Flatlist />

Like WhatsApp and other chat apps, the messages start at the bottom.

After fetching the messages from my API, I call

this.myFlatList.scrollToEnd({animated: false});

But it scrolls somewhere in the middle and sometimes with fewer items to the bottom and sometimes it does nothing.

How can I scroll initially to the bottom?

My chat messages have different heights, so I can't calculate the height.

like image 684
yooouuri Avatar asked Jan 27 '18 15:01

yooouuri


2 Answers

I had similar issue. If you want to have you chat messages start at the bottom, you could set "inverted" to true and display your messages and time tag in an opposite direction.

Check here for "inverted" property for FlatList. https://facebook.github.io/react-native/docs/flatlist#inverted

If you want to have you chat messages start at the top, which is what I am trying to achieve. I could not find a solution in FlatList, because as you said, the heights are different, I could not use getItemLayout which make "scrollToEnd" behave in a strange way.

I follow the approach that @My Mai mentioned, using ScrollView instead and do scrollToEnd({animated: false}) in a setTimeout function. Besides, I added a state to hide the content until scrollToEnd is done, so user would not be seeing any scrolling.

like image 92
CAIsoul Avatar answered Sep 19 '22 17:09

CAIsoul


Set initialScrollIndex to your data set's length - 1.

I.e.

<Flatlist
data={dataSet}
initialScrollIndex={dataSet.length - 1}
/>
like image 36
peralmq Avatar answered Sep 19 '22 17:09

peralmq