Gatsby: unique "key" prop

1.1k Views Asked by At

I'm trying to get a category of data from contentful through Graphql and put out on the web page but not working right now ..

Success

  • Get id, image, slug title

Fail

  • The only title can not put out on the web page .

Error

index.js:2177 Warning: Each child in a list should have a unique "key" prop. Blockquote Check the render method of StaticQueryDataRenderer.

index.js

import React from 'react'
import { graphql, navigate, StaticQuery } from 'gatsby'
import './home.css'

export default () => (
   <StaticQuery
     query={graphql` 
  query HomeQuery {
    allContentfulBlog(
   
        sort: { fields: [createdAt], order: DESC }     
      ) {
      edges {
        node {
          id
          slug
          title
          category {
            id
           
          }
        }
      }
    }
  }
`}
     render={data => (
        <div className='feed'>
        {data.allContentfulBlog.edges.map(edge => (
            <div key={edge.node.id} className='card'
        onClick={() => navigate(`/blog/${edge.node.slug}`)} >
        {edge.node.category.map(categories=> (
            <p className='card__category'>{categories.category}</p>
        ))}
        </div>
        ))}
      </div>
     )}
   />
 )
1

There are 1 best solutions below

0
On

As the error shows, it's a warning, not an error. It won't break your code.

The key is a prop that should be provided for all looped items. It is a special string attribute you need to include when creating lists of elements in order to help React identify which items have changed, are added, or are removed. It should be a unique value and it's not a good practice to assign the index of the loop (since it's not unique). You can concatenate the index plus another variable (such as the name or title).

You just need to:

   {edge.node.category.map( ss => (
        return <p key={ss.title} className='card__category' >{ss.title}</p>
     ))}

Spot the key and the return. All mapped elements must return something.

I would suggest the following readings: