Lama N
Lama N

Reputation: 3

Looping through object and using map doesn't return jsx

I am trying to loop through object of objects and using map to list the item and I am getting this object from redux. I can console.log the value but jsx returns nothing. I tried removing {} and return and using () only but still it is not rendering anything.

My posts object looks like

posts = { 1: {id: 1, title: "Hello world"} }

Component.js

renderList(){
   const { posts } = this.props;
   Object.keys(posts).map(key => {
     console.log(`${key} and ${posts[key].title}`);
     return (
       <li key={key} className="list-group-item">
          {posts[key].title}
       </li>
     );
   });
}

render(){
    return (
      <div>
        <h2>Posts</h2>
        <ul className="list-group">{this.renderList()}</ul>
      </div>
    );
}

I can't figure out what I am doing wrong.

Upvotes: 0

Views: 672

Answers (1)

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

Your renderList method does not have a return statement. Depending on if your version of React you can either return an array here or you need to wrap it in a div (or in this case put the ul into it).

renderListOnReact16(){
   const { posts } = this.props;
   return Object.keys(posts).map(key => {
     console.log(`${key} and ${posts[key].title}`);
     return (
       <li key={key} className="list-group-item">
          {posts[key].title}
       </li>
     );
   });
}

renderOnReact16(){
    return (
      <div>
        <h2>Posts</h2>
        <ul className="list-group">{this.renderList()}</ul>
      </div>
    );
}

renderListOnReact15(){
   const { posts } = this.props;
   return (
     <ul className="list-group">
      {Object.keys(posts).map(key => {
         console.log(`${key} and ${posts[key].title}`);
         return (
           <li key={key} className="list-group-item">
            {posts[key].title}
           </li>
         );
     })}
   );
}

renderOnReact16(){
    return (
      <div>
        <h2>Posts</h2>
        {this.renderList()}
      </div>
    );
}

Upvotes: 3

Related Questions