Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React, what is the function of the key attribute in html tag

Tags:

reactjs

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>;
})}
like image 311
MLhacker Avatar asked Nov 18 '16 02:11

MLhacker


1 Answers

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 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 tell react to render:

<ul>
    <li>England</li>
    <li>Germany</li>
</ul>

There's multiple ways to update the DOM:

  • Change inner text of second <li>
  • Remove second <li> and add a new one

Without key, react don't know which one to choose.

You can read more in the docs.

like image 102
Niyoko Avatar answered Oct 22 '22 05:10

Niyoko