skip to Main Content

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

3

Answers


  1. 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}
        />
      )
    })}
    
    Login or Signup to reply.
  2. 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}
                />;
        )
      })} 
    
    Login or Signup to reply.
  3. The map function requires a return statement inside the curly braces {}. In your case, you’re using curly braces instead of parentheses (). You should replace the curly braces with parentheses to properly return the PostList component from the map function. This is the corrected code:-

    {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}
      />
    ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search