MiniGunnR MiniGunnR - 1 month ago 13
React JSX Question

How does the map function work in React.js?

I'm following the ReactJS tutorial from www.tutorialpoints.com and I'm at this page

In a nutshell it provides the following data in JSON format:

this.state = {
data:
[
{
"id":1,
"name":"Foo",
"age":"20"
},

{
"id":2,
"name":"Bar",
"age":"30"
},

{
"id":3,
"name":"Baz",
"age":"40"
}
]
}


and is looping through it with the map function below:

{this.state.data.map((person, i) => <TableRow key = {i} data = {person} />)}


What I fail to understand is why are they using a tuple (person, i) to target EACH object and how is the
key = {i}
part of the code working. I have tried removing the
key
part and the code still works. From further reading I understood that it helps reload only the specific data that has been changed instead of the whole dataset, but I'm not sure.

Can anyone go through ONLY the loop in that example line by line to clarify how this works?

Answer

Consider your .map() returns 10 items. When you change one of the 10 item, say 5th item, React won't know which element to change in particular without the key. So, it will re-render the entire items of the .map().

If you provide a key, the element with that key will be re-renders leaving the other 9 items undisturbed. This is to improve performance.

[UPDATE]

The key is reserved to identify an React element uniquely. It don't need to be i, it can be any random string. Personally, I use shortid to generate random unique key.

{this.state.data.map((person) => <TableRow key = {shortid.generate()} data = {person} />)}

React won't add it's reference ids(data-reactid) when you have a array of React elements. When you try to render that array, React will append your key to its data-reactid during normalization.

Array of elements without key

<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1" role="row">

Array of elements withkey

<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1.$123" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1.$124" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1.$125" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1.$126" role="row">
<tr class="" data-version="1.0.0" data-reactid=".0.2.2.1.0.0.1.$127" role="row">

The number after $ is the key value you supply to that component. By this, React can uniquely identify a component.

Latest version of React won't expose the data-reactid in the DOM.

Read this for better understanding

Comments