reactjsarraysobjectnext.jsarray.prototype.map

unable to map array of objects with key indicator


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


Solution

  • 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}
        />
      )
    })}