Home > Enterprise >  React map inside map
React map inside map

Time:03-31

      {posts.map((post) =>
        posts.comments?.map((comment) => (
          <Posts key={post._id} post={post} comment={comment} />
        ))
      )}

I want to be able to do something like this, where I loop through posts and comments and send every comment and post as a prop to Posts component, but its not working, how can I do it?

CodePudding user response:

with your code, you send every comment seperatly to you Posts component and create a Posts component for every comment.

I think your posts array is something like this:

const posts = [{id: 1, comments: [], name: 'post_name', ...}, {...}, ]

so you need just one map

posts.map(post => {
    return (
        <Posts key={post._id} post={post}/>
    )
})

and in Posts component, you have "post" as a prop. just map your post.comments here:

functional component example of Posts:

const Posts = ({post}) => {
...

return (
    post.comments.length > 0 && (
        post.comments.map(comment => {
            return (
               <div>{comment}<div/>
            )
        })
    )
)}

 

CodePudding user response:

You need to change posts.comments to post.comments inside first map function. I assume that array comments is in each object in the main array.

{posts.map((post) =>
    post.comments?.map((comment) => (
      <Posts key={post._id} post={post} comment={comment} />
    ))
  )}
  • Related