Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Given an array, render the elements in reverse order efficiently

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?

like image 627
MarkPickett Avatar asked Jun 06 '16 18:06

MarkPickett


People also ask

How do you render an array in reverse 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.

How do I iterate a map in reverse order in react JS?

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.

Which function is used to reverse the order of the 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.


1 Answers

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;
like image 196
Alfrex92 Avatar answered Oct 19 '22 12:10

Alfrex92