LoginSignup
1
0

More than 1 year has passed since last update.

Each child in a list should have a unique "key" prop.エラーについて

Posted at

Each child in a list should have a unique "key" prop.
のようなエラーが出ました。
こちらの解決法についてmemoしていきたいと思います。

原因としては、ReactはJSXの配列からlistを作成する際、keyを呼び出す側につける必要があり、
今回Main.jsのWorksというコンポーネントにkeyがなかったので、
そのエラーでした。

Main.js
 <div className="worksContainer">
          <h2>WORKS</h2>
          {worksList.map((worksItem) => {
            return (
              <Works
                name={worksItem.name}
                image={worksItem.image}
                skill={worksItem.skill}
                introduction={worksItem.introduction}
              />
            );
          })}
        </div>

この状態だと上記のエラーが出てしまい、

Main.js
 <div className="worksContainer">
          <h2>WORKS</h2>
          {worksList.map((worksItem) => {
            return (
              <Works
                key ={""}
                name={worksItem.name}
                image={worksItem.image}
                skill={worksItem.skill}
                introduction={worksItem.introduction}
              />
            );
          })}
        </div>

keyを入れてあげるとエラーが消えました。

ReactはコンポーネントとDOMの関係性を作るためにkeyを使用していて、ライブラリーはこの関係性をコンポーネントをレンダリングするかどうかの判断基準に使用しているとのこと。

参考記事:https://sentry.io/answers/unique-key-prop/
公式:https://reactjs.org/docs/lists-and-keys.html

1
0
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
1
0