Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Unable to map through array of objects

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
like image 235
Deke Avatar asked Mar 05 '23 20:03

Deke


2 Answers

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)}
like image 162
Hemadri Dasari Avatar answered Mar 09 '23 10:03

Hemadri Dasari


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>)
    }
like image 30
Dacre Denny Avatar answered Mar 09 '23 09:03

Dacre Denny