Rendering Arrays
Loading "Intro to Rendering Arrays"
Run locally for transcripts
One of the more tricky things with React is the requirement of a
key
prop when
you attempt to render a list of elements.If we want to render a list like this, then there's no problem:
const ui = (
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
)
But rendering an array of elements is very common:
const list = ['One', 'Two', 'Three']
const ui = (
<ul>
{list.map(listItem => (
<li>{listItem}</li>
))}
</ul>
)
Those will generate the same HTML, but what it actually does is slightly
different. Let's re-write it to see that difference:
const list = ['One', 'Two', 'Three']
const listUI = list.map(listItem => <li>{listItem}</li>)
// notice that listUI is an array
const ui = <ul>{listUI}</ul>
So we're interpolating an array of renderable elements. This is totally
acceptable, but it has interesting implications for when things change over
time.
We haven't covered things changing over time yet, but a warning's going to
show up any time you render an array regardless of whether that array changes
so we're going to address that here.
If you were to somehow update that list with an added item and tell React to
update the UI, React doesn't really know whether you added an item in the
middle, beginning, or end. And the same goes for when you remove an item (it
doesn't know whether that changes is in the middle, beginning, or end either).
Or maybe you removed them all and replaced them with completely new values.
React just doesn't have enough information to know what to do about what you've
done to the array.
In simple cases (like the
One
, Two
, Three
example above), it's not a big
deal, because React's best-guess works out ok. However, if any of those React
elements represent a component that is maintaining state, that can be pretty
problematic, which this exercise demonstrates.