Search code examples
react-nativechatreact-native-gifted-chat

How to determine the message rendering order in React Native Gifted Chat?


I am wondering how I could determine the message rendering order?

At first I thought it would use the createdAt Date object to determine the rendering, but it doesn't.

(As you see it doesn't render based on Date (2019 first, 2018, 2017, 2016, and 2019 once again)

As you see it doesn't render based on Date (2019 first, 2018, 2017, 2016, and 2019 once again

I am wondering how can I fix the order to show the newest messages first. My initial message array looks like:

const [messages, setMessages] = useState([
    {
      _id: 'gdfsdfasdfasdfasdfas',
      text: 'Test Test 2',
      createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'aereraesaresraesraes',
      text: 'Test Test',
      createdAt: new Date(Date.UTC(2017, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'dasfadsfdfasfadasdasd',
      text: 'What\'s up ;)',
      createdAt: new Date(Date.UTC(2018, 5, 11, 17, 20, 1)),
      user: {
        _id: 2,
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
    {
      _id: 'dasdasfdasfdasf',
      text: 'Hello developer',
      createdAt: new Date(Date.UTC(2019, 5, 11, 17, 20, 1)),
      user: {
        _id: 'ewrqqewrewrqrqewrewq',
        name: 'React Native',
        avatar: 'https://placeimg.com/140/140/any',
      },
    },
  ]);

Solution

  • This issue was a real pain for me as well. I finally made it work. As you already have createdAt new JS date format further you just need to sort the array. react-native-gifted-chat doesn't do it by default. So before you set state use the below sorting method to render chat with proper structure.

    data.sort((a, b) => b.createdAt - a.createdAt)