unable to map array of objects with key indicator

47 Views Asked by At

please check the screenshot how can we map array of objects.

{posts.map((post) => {
            <PostList
              id={post.id}
              key={post.id}
              username={post?.data?.username}
              profileImage={post?.data?.profileImage}
              postImage={post?.data?.postImage}
              description={post?.data?.description}
            />;
          })}

enter image description here

2

There are 2 best solutions below

0
Xiduzo On BEST ANSWER

Your .map function is not returning anything

{posts.map((post) => { // Open new scope
  // Nothing being returned here
  <PostList
    id={post.id}
    key={post.id}
    username={post?.data?.username}
    profileImage={post?.data?.profileImage}
    postImage={post?.data?.postImage}
    description={post?.data?.description}
  />;
})}

You can solve this in two ways

1: directly returning the <PostList> with an implicit return

{posts.map((post) => ( // Implicit return
  <PostList
    id={post.id}
    key={post.id}
    username={post?.data?.username}
    profileImage={post?.data?.profileImage}
    postImage={post?.data?.postImage}
    description={post?.data?.description}
  />
))}

or 2. using an explicit return

{posts.map((post) => { // Open new scope
  // We can do stuff here
  // Like a console.log(post)
  return ( // Explicit return
    <PostList
      id={post.id}
      key={post.id}
      username={post?.data?.username}
      profileImage={post?.data?.profileImage}
      postImage={post?.data?.postImage}
      description={post?.data?.description}
    />
  )
})}
0
Saad Ali On

what is your problem exactly? The codes looks good the change I think you made in your code is to return the component inside the map like this

{posts.map((post) => {
       return (
            <PostList
              id={post.id}
              key={post.id}
              username={post?.data?.username}
              profileImage={post?.data?.profileImage}
              postImage={post?.data?.postImage}
              description={post?.data?.description}
            />;
    )
  })}