Reputation: 1502
What is the function of the key attribute in the p tag? I inspected the dom, and I expected to see p tags for each element of the taco list as expressed in <p taco-1>
, but it's just <p>
. Any explanation will be much appreciated.
{this.props.tacos.map( ( taco, i ) => {
return <p key={ `taco-${ i }` }>{ taco }</p>;
})}
Upvotes: 21
Views: 25295
Reputation: 7662
It is used by React in a collection of component to see which element is inserted, which element is removed and which element is updated. Without the key
attribute, it's hard to determine how to update the collection.
For example, see component collection below:
<ul>
<li>England</li>
<li>France</li>
</ul>
and then next state tells React to render:
<ul>
<li>England</li>
<li>Germany</li>
</ul>
There's multiple ways to update the DOM:
<li>
<li>
and add a new oneWithout key, React don't know which one to choose.
You can read more in the docs: React.dev › Rendering Lists › Why does React need keys?
Upvotes: 33