Reputation: 979
I was learning React and wanted to use map() function. Here i the code:
class App extends Component {
state = { car:[
{carTitle:'Toyota'},
{carTitle: 'Honda'},
{cartitle: 'Chevrolet'}
] };
render() {
return ( <div>
{this.state.car.map((item, index)=>
<h1>{item.carTitle}</h1>
)}
</div> );
}
}
The question is why if I use
{this.state.car.map((item, index)=>
<h1>{item[index].carTitle}</h1>
I get an error. Since I have array of objects, I think it is logical to use {item[index].carTitle}
. But if I use <h1>{item.carTitle}</h1>
, all works ok. Why? Did I misunderstood something?
Upvotes: 0
Views: 94
Reputation: 945
When you use .map()
you need to pass a function as a callback, like the one you are already passing: .map( (item, index) => ... )
The first argument of this callback function, item
, is the current element that is been processed in the array. index
is the current position.
item
already returns the content of each position of the array, in this case each object that you defined in car
.
So, your second example, item[index].carTitle
, is incorrect because you are trying to access an array position that doesn't exist inside each object.
Also, everytime you use a .map()
in ReactJS applications, you need to specify a key
to the element you are returning inside this function, in this case: <h1 key={index}>{{car.carTitle}}</h1>
.
Golden tip: to make your code clearer and avoid confusion you should rename car
to cars
, as it is a list of cars, and instead of using item
you should use car
. It will make your code more legible and anybody that reads your code can understand it easier than if you are using generic names. So it would look something like this:
cars: [
{carTitle:'Toyota'},
{carTitle: 'Honda'},
{cartitle: 'Chevrolet'}
]
and:
{this.state.cars.map( (car, index) => {
<h1 hey={index}>{{car.carTitle}}</h1>
})}
Further readings:
Upvotes: 3