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?
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.
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.
The render() method is the only required method in a class component.
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 />, ...
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.
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