LoginSignup
17
7

More than 1 year has passed since last update.

GatsbyでMissing "key" prop for element in iteratorが出る

Posted at

はじめに

こんにちは。クワガタかカブトムシかでいうとクワガタ派です、筆者です :raising_hand:

さて、Gatsbyで作ったほぼほぼチュートリアルでいじってないコードに機能追加する機会がありました。
Reactもあんまり理解していないが故に、お作法でつまづきました。

GatsbyでMissing "key" prop for element in iteratorが出る

Contentfulからpost一覧を取得して、postの数だけitemを生成したいのですが、スクリーンショットのように怒られたました :innocent:

const posts = data.allContentfulPost.edges
return (
  <Wrapper>
    <List>
      {posts.map(({ node }) => {
        return (
          <ArticleItem
            title={node.title}
            heroImage={node.heroImage}
            slug={node.slug}
          />
        )
      })}
    </List>
  </Wrapper>
)

1.png

原因

ArticleItemにkeyを渡してないため。

Reactのドキュメントには以下の通りの記載があります。

Keys should be given to the elements inside the array to give the elements a stable identity:

解決策

以下のようにArticleItemにkeyで一意の値を渡してあげれば大丈夫です :ok_hand:

  const posts = data.allContentfulPost.edges
  return (
    <Wrapper>
      <List>
        {posts.map(({ node }) => {
          return (
            <ArticleItem
+             key={node.slug}
              title={node.title}
              heroImage={node.heroImage}
              slug={node.slug}
            />
          )
        })}
      </List>
    </Wrapper>
  )

また、Reactのドキュメントに記載の通り、最悪indexを渡せばいいそうです。

おわりに

小さなことですが、知らないことでしたし、こういうことで怒ってくれるのがちょっとうれしいとも感じました。
引き続きググりながら機能追加進めつつ、コードの理解を深めていこうと思います:bow:

それでは:bow:

17
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
7