Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScrollToEnd after update data for Flatlist

I'm making a chat box with Flatlist. I want to add a new item to data then scroll to bottom of list. I use scrollToEnd method but it did not work. How can I do this?

<FlatList
        ref="flatList"
        data={this.state.data}
        extraData = {this.state}
        renderItem={({item}) => <Text style={styles.chatFlatListItem}>{item.chat}</Text>}
/>

AddChat(_chat){
    var arr = this.state.data;
    arr.push({key: arr.length, chat: _chat});
    var _data = {};
    _data["data"] = arr;
    this.setState(_data);
    this.refs.flatList.scrollToEnd();
 }
like image 235
Tuan Nguyen Quoc Avatar asked Sep 19 '17 15:09

Tuan Nguyen Quoc


People also ask

How do I refresh FlatList data in React Native?

To implement pull to refresh FlatList with React Native, we can set the refreshing and onRefresh props. to set the refreshing prop to isFetching , which is true when we're getting data for the FlatList . And we set onRefresh to the onRefresh which sets refreshing to true and then set it back to false after 2 seconds.

How do I use extra data on FlatList?

flatlist-simpleBy passing extraData={selectedId} to FlatList we make sure FlatList itself will re-render when the state changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is a PureComponent and the prop comparison will not show any changes.

How do I use a scroll to end in FlatList?

To scroll to end of FlatList after displaying the keyboard with React Native, we can set the onLayour prop to a function that calls scrollToEnd on the FlatList's ref. to set onLayout to a function that calls flatListRef. current. scrollToEnd to scroll the FlatList to the end.


3 Answers

I found a better solution,scrollToEnd() is not working because it is triggered before the change is made to the FlatList.
Since it inherits from ScrollView the best way here is to call scrollToEnd() in onContentSizeChange like so :

<FlatList
            ref = "flatList"
            onContentSizeChange={()=> this.refs.flatList.scrollToEnd()} /> 
like image 127
Ourabi Avatar answered Oct 27 '22 08:10

Ourabi


Thanks @Kernael, just add a timeout like so:

setTimeout(() => this.refs.flatList.scrollToEnd(), 200)
like image 26
Tuan Nguyen Quoc Avatar answered Oct 27 '22 07:10

Tuan Nguyen Quoc


const flatList = React.useRef(null)
<FlatList
        ref={flatList}
        onContentSizeChange={() => {
            flatList.current.scrollToEnd();
        }}
        data={this.state.data}
        extraData = {this.state}
        renderItem={({item}) => <Text style={styles.chatFlatListItem}>{item.chat}</Text>}
/>

try this,it works.

like image 36
root Avatar answered Oct 27 '22 07:10

root