There are many solutions posted out there in terms of iterating an array and generating JSX elements. All of them are good, but all of them used an index directly in a loop. We are recommended to use unique id from data as a key, but when we do not have a unique id from each object in the array we will use index as a key, but you are not recommended to use an index as a key directly.
One more thing why we go for .map, but why not .foEach because .map returns a new array. There are different ways of doing .map these days.
Below different versions of using .map illustrates in detail about how to use a unique key and how to use .map for looping JSX elements.
.map without return when returning single a JSX element and unique id from data as a key version:
const {objects} = this.state;
<tbody>
{objects.map(object => <ObjectRow obj={object} key={object.id} />)}
</tbody>
.map without return when returning multiple JSX elements and unique id from data as a key version
const {objects} = this.state;
<tbody>
{objects.map(object => (
<div key={object.id}>
<ObjectRow obj={object} />
</div>
))}
</tbody>
.map without return when returning a single JSX element and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => <ObjectRow obj={object} key={`Key${index}`} />)}
</tbody>
.map without return when returning multiple JSX elements and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => (
<div key={`Key${index}`}>
<ObjectRow obj={object} />
</div>
))}
</tbody>
.map with return when returning multiple JSX elements and index as a key version:
const {objects} = this.state;
<tbody>
{objects.map((object, index) => {
return (
<div key={`Key${index}`}>
<ObjectRow obj={object} />
</div>
)
})}
</tbody>
.map with return when returning multiple JSX elements and unique id from data as a key version:
const {objects} = this.state;
<tbody>
{objects.map(object => {
return (
<div key={object.id}>
<ObjectRow obj={object} />
</div>
)
})}
</tbody>
The other way is
render() {
const {objects} = this.state;
const objectItems = objects.map(object => {
return (
<div key={object.id}>
<ObjectRow obj={object} />
</div>
)
})
return(
<div>
<tbody>
{objectItems}
</tbody>
</div>
)
}
let todos = this.props.todos.map((todo) => {return <h1>{todo.title}</h1>})
– Pintsizelet todos = this.props.todos.map(t => <h1>{t.title}</h1>)
:) – Pintsizefor loop
. Afor loop
doesn't really return anything, which is why we have to push values into an array and return the array. If you're looking for more explanation, checkout How To Loop Inside React JSX - React FAQ – Quintain