Why am I not able to map through array of objects. I have used this map before but it doesn't seem to be working in this component. Any idea what is wrong?
import React, { Component } from "react";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
people: [
{name:"a", age: 21},
{name:"b", age: 22},
{name:"c", age: 23}
]
}
this.clickListnerHandler = this.clickListnerHandler.bind(this)
}
clickListnerHandler(e){
console.log(this.state.people)
}
render(){
return (
<div>
{this.state.people.map((detail, index) =>
{detail.name}
)}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>
)
}
}
export default Home
Change
{this.state.people.map((detail, index) =>
{detail.name}
)}
To
these days there are two ways to use .map i.e., by using return and without return. You should use ( or { when your code is multi line inside .map function
Without return
{this.state.people.map(detail=> (
detail.name
))}
With return
{this.state.people.map(detail=> {
return detail.name
})}
Or if it is a single line of code, in which your .map
returns, then you don't need to return (
or {
. Please take a look at the below code:
{this.state.people.map(detail=> detail.name)}
Your use of syntax in the map
callback is slightly incorrect, which is causing the map function to not return anything. Consider revising your render()
method in the following way:
render(){
return (<div>
{this.state.people.map((detail, index) => {
// detail.name is returned for each item mapped
return detail.name;
})}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>)
}
Alternatively, you can use the following syntax which is shorthand equivalent to what is shown above:
render(){
return (<div>
{this.state.people.map((detail, index) => detail.name)}
<button
onClick={this.clickListnerHandler}
type="button" >Click on me</button>
</div>)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With