react-nativereact-native-flatlist

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();
 }


Solution

  • 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()} />