2

I am learning getStaticProps in NextJS. I am making use of the https://jsonplaceholder.typicode.com/posts API to render posts on a page. Following is my code for the JS file:

function PostList({posts}){
    return (
        <>
        <h1>
            List of posts
        </h1>
        {
            posts.map(post => {
                return (
                <>
                    <div key={post.id}>
                        <h2>{post.id} {post.title}</h2>
                    </div>
                    <hr/>
                </>    
                    
                )
            })
        }
        </>
        )

}

export async function getStaticProps(){
    const response = await fetch('https://jsonplaceholder.typicode.com/posts')
    const data = await response.json()
    return {
        props: {
            posts: data
        }
    }
}

export default PostList

However, the console gives me the following error:

react_devtools_backend.js:4045 Warning: Each child in a list should have a unique "key" prop.

I am assigning the ID of each post as the key in the "div" tag. Yet, I am still getting the error. Is there something wrong with my code or is there something else I am supposed to be adding?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
mukunda
  • 301
  • 1
  • 4
  • 13
  • 1
    Change `<>...>` inside your `map` to `...` (and remove that key from `div`). (Add `import { Fragment } from 'react';`) – brc-dd Dec 25 '21 at 18:32
  • 2
    Does this answer your question? [Can I add a key prop to a React fragment?](https://stackoverflow.com/questions/59390955/can-i-add-a-key-prop-to-a-react-fragment) – noobie Dec 25 '21 at 18:40
  • @brc-dd Your answer fixed the error. Any particular reason why assigning the ID in the div tag was causing the problem? – mukunda Dec 25 '21 at 18:42
  • 1
    @mukunda `div` is not a (direct) child of the array. `<>...>` is. `<>` is a shortcut of writing `React.Fragment`. Read the linked question. – brc-dd Dec 25 '21 at 18:43

2 Answers2

4

Instead of <></> use the below form of Fragment which allows to set the key.

<React.Fragment key={item.id}>... </React.Fragment>

For Reference

Mukesh Bhati
  • 504
  • 4
  • 5
2

You just have to add a key attribute to the tag surrounding dom node inside the map.

function PostList({posts}){
    return (
        <>
        <h1>
            List of posts
        </h1>
        {
            posts.map(post => {
                return (
                    <div key={post.id}>
                        <h2>{post.id} {post.title}</h2>
                    <hr/>
                    </div>  
                )
            })
        }
        </div>
        )

}
DoneDeal0
  • 5,273
  • 13
  • 55
  • 114