2

I am new to Typscript with React and I am getting this error message on my Google console Inspect element. I checked many posts over this but unable to understand what went wrong here. Can someone help to rectify the mistake in my code?

index.js:1 Warning: Each child in a list should have a unique "key" prop.

Check the render method of PostList. See

in div (at PostList.tsx:19)
in PostList (at pages/index.tsx:25)
in div (at pages/index.tsx:21)
in IndexPage (at App.tsx:68)
in component (created by Context.Consumer)
in Route (at App.tsx:65)
in div (at App.tsx:64)
in div (at App.tsx:85)
in Router (created by BrowserRouter)
in BrowserRouter (at App.tsx:84)
in App (at src/index.tsx:8)
 export default class PostList extends React.Component <Props, Post>{
 renderPosts(){
    const posts=Object.values (this.props.posts);
    return posts.map((n)=> <div>
         <h2> <Link to= {`/posts/${n._id}`}> {n.title}</Link></h2>
         </div>);
}
render(){
    return(
        <div>
            { this.renderPosts() }
        </div>
    )
 }
 }
Community
  • 1
  • 1
Richa
  • 151
  • 1
  • 3
  • 8
  • Does this answer your question? [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – Emile Bergeron Jan 08 '20 at 15:34

3 Answers3

6

Use key with the wrapping tag div

return posts.map((n, index)=> <div key={index}>
             <h2> <Link to= {`/posts/${n._id}`}> {n.title}</Link></h2>
             </div>);

unique keys are better, you should only use index as the last resort

key={n._id}

This is preferred.

kooskoos
  • 4,622
  • 1
  • 12
  • 29
1

When you return html in a map function, each element should have a unique key.

Example: <div key={n._id}>...</div>

You can read more about this here: https://reactjs.org/docs/lists-and-keys.html

Kristoffer Lund
  • 209
  • 3
  • 14
0

Whenever you do a map operation in react, the loop needs to have a unique key to identify whether it requires re-rendering during react rendering process. Read through the below link for more details refer keys section

nbsamurai
  • 346
  • 4
  • 13