I currently render a list in the typical React-style. The list is passed as an array prop, and I map over it like so:
{this.props.myList.map(createListItem, this)}
So when a new element is added, it appears like the latest item was added to the end of the list.
I would like it so the latest item appears at the top. i.e. everything appears in reverse-chronological order.
The two options I've come up with so far are: 1) Reverse the list, creating a new array each time something is added, and pass this reversed list as the prop. 2) Use shift.
But they're both unappealing because of performance.
I'm not aware of Javascript supporting mapping in reverse order. I've been trying a for-loop but I haven't been able to get it to work.
What is the idiomatic way to render an array in reverse order in React?
Call the slice() method on the array to create a shallow copy. Call the reverse() method on the copy. Store the result in a variable.
To use the map() method on an array in reverse order in React: Use the spread syntax (...) to get a copy of the array. Use the reverse() method to reverse the copied array. Call the map() method on the reversed array.
reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.
If you need to display a list in the UI in reverse order you can also use
flex-direction: row-reverse;
or
flex-direction: column-reverse;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With