There are many solutions posted out there interms of iterating an array and generating jsx elements. All of them are good but all of them used index directly in loop. We are recommended to use unique id from data as a key but when we do not have unique id from each object in the array we will use index as a key but you are not recommended to use index as a key directly.
One more thing why we go for .map but why not .foEach because .map returns an new array. There are different ways of doing .map these days.
Below different version of using .map illustrates in detail about how to use unique key and how to use .map for looping jsx elements
.map without return when returning single jsx element and unique id from data as a key version
const {objects} = this.state;
{objects.map(object => )}
.map without return when returning multiple jsx elements and unique id from data as a key version
const {objects} = this.state;
{objects.map(object => (
))}
.map without return when returning single jsx element and index as a key version
const {objects} = this.state;
{objects.map((object, index) => )}
.map without return when returning multiple jsx elements and index as a key version
const {objects} = this.state;
{objects.map((object, index) => (
))}
.map with return when returning multiple jsx elements and index as a key version
const {objects} = this.state;
{objects.map((object, index) => {
return (
)
})}
.map with return when returning multiple jsx elements and unique id from data as a key version
const {objects} = this.state;
{objects.map(object => {
return (
)
})}
The other way is
render(){
const {objects} = this.state;
const objectItems = objects.map(object => {
return (
)
})
return(
{objectItems}
)
}
No comments:
Post a Comment