Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I guarantee the render order of an array of React components?

Tags:

arrays

reactjs

I have an array of react components I'm trying to render in a specific order. Something like this:

render: function() {
  var items = stock.map(function(item) {
    return <NewLI data={item} key={item.id}/>
  }
  return <ul>{items}</ul>
}

My problem is that React is not returning the li's in the order of the original array (the actual component is more complex than a single li, but it is properly wrapped in a div).

so if print the id keys of items, I get this:

items.forEach(function(a) { console.log(a.id) })
> 1
> 2
> 3
> 4

but my React render looks like this:

<ul>
  <li...>2</li>
  <li...>3</li>
  <li...>4</li>
  <li...>1</li>
</ul>

Is this expected behavior? Is there a way to guarantee the order?

like image 800
AJFarkas Avatar asked Aug 31 '15 22:08

AJFarkas


People also ask

How React decides which components to re render?

React has to run its diffing algorithm on each of those components to check whether it should update the UI. All your code in these render functions or function components will be executed again.

What's the typical pattern for rendering a list of components from an array in React?

The pattern for rendering a list of components from an array of data can be done by mapping all individual custom pieces of data to the component. With the map function, we will map every element data of the array to the custom components in a single line of code.

Is it mandatory for each React component to have a render () function?

The render() method is the only required method in a class component.

Can I store React components in an array?

Certainly. If you want to pass instances of the component, what you're doing is fine except that you need to close those JSX tags: { src: <SVGComponent1 />, ...


1 Answers

This is not expected behavior. React always renders arrays in the order of the elements.

If there are items with conflicting key values, only the latest element will render, but that doesn't look like the case here, since all four of your elements are rendered.

Any chance that is a custom .map() function that returns an object, and not another array? Objects will render in key-iteration order, which isn't necessarily guaranteed consistent across browsers.

like image 168
Sean Adkinson Avatar answered Oct 10 '22 20:10

Sean Adkinson