Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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) =><TableRowkey = {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

Post a Comment for "How Does The Map Function Work In React.js?"