Home > Software design >  ES6 Map Error: "Warning: Each child in a list should have a unique "key" prop"
ES6 Map Error: "Warning: Each child in a list should have a unique "key" prop"

Time:10-14

One of the React elements returns an error by saying that the key is missing even though it's included. The red error squiggle line is always flagged on the next line from the key={post.id}. If any suggestions and comment, I'd appreciate.

Update: This is the entire code

export const Feed = () => {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    db.collection('posts').onSnapshot(snapshot => setPosts(snapshot.docs.map(doc => doc.data())))
  }, [])

  return (
    <div className='feed'>
      <div className='feed__header'>
        <h2>Home</h2>
      </div>

      <TweetBox />
        {posts.map(post => (
          <Post
            key={post.id}
            username={post.username}
            displayName={post.displayName}
            verified={post.verified}
            text={post.text}
            avatar={post.avatar}
            image={post.image}
          />
        ))}
    </div>
  )
}

export default Feed

And this is the 'posts' array stored in the Firebase: enter image description here

CodePudding user response:

Try to add another outter block

For example:

    {posts.map((post, index) => (
              <div key={index}>
                <Post
                key={post.id}
                username={post.username} //<-red squiggle lined//
                displayName={post.displayName}
                verified={post.verified}
                text={post.text}
                avatar={post.avatar}
                image={post.image}
                />
              </div>
            ))} 

CodePudding user response:

{posts.map((post, index) => (
                <Post
                    key={`${post.id}-${index}`}
                    username={post.username} //<-red squiggle lined//
                    displayName={post.displayName}
                    verified={post.verified}
                    text={post.text}
                    avatar={post.avatar}
                    image={post.image}
                />
            ))}

  • Related