Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new elements on FlatList like Chat apps?

Is there a way to add new elements in the FlatList stack in React Native, vertically but bottom each other? like in Chat applications, where the new message gets to be added below the old one.

I have tried the Inverted property, however, It does not serve what I'm trying to achieve.

      <FlatList
      data={this.state.messages}
      renderItem={({ item }) => (
        <ChatRow mykey={item.messageID}>{item.text}</ChatRow>
      )}
      onEndReache={this.handleChatUpdate.bind(this)}
      vertical="true"
    />

ChatRow component

     <View style={styles.chatRow}>
      <Badge warning style={styles.chatRowSender}>
        <Text>{this.props.children}</Text>
      </Badge>
    </View>
like image 868
Sobiaholic Avatar asked Dec 10 '25 15:12

Sobiaholic


1 Answers

Inverting your FlatList is a step in the right direction, but you also need to make sure you maintain the order of this.state.messages. You should timestamp your messages, and sort them so that the earliest messages are at the front of the list, if you have a timestamp you can achieve this via:

<FlatList
  inverted
  //I use .slice to duplicate the array here because
  //.sort mutates the array and we don't want to mutate state ever
  data={
    this.state.messages.slice().sort(
     (a,b) => a.timestamp.valueOf() - b.timestamp.valueOf(
  )}
/>

Now your messages with the latest timestamp will appear at the bottom of the list, the user will scroll beginning from the bottom, and the user can scroll up to see older messages similar to an SMS app.

like image 176
Robbie Milejczak Avatar answered Dec 13 '25 05:12

Robbie Milejczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!