Home > Enterprise >  "Warning: Each child in a list should have a unique 'key' prop" error in NextJS
"Warning: Each child in a list should have a unique 'key' prop" error in NextJS

Time:12-26

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?

CodePudding user response:

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

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

For Reference

CodePudding user response:

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>
        )

}

  • Related