✨
ReactでよくやるCheck the top-level render call using <div>. というkeyのエラーについて
以下の公式に書いてあります。
以下のようなものを書くとエラーが出ます。
<div>
{allCategoryPost.map((categoryItems) => {
return (
<>
<MenuParts
categoryItems={categoryItems}
currentName={currentName}
contentsPath={contentsPath}
/>
</>
);
})}
</div>
Check the top-level render call using <div>. See https://reactjs.org/link/warning-keys for more information.
以下のように、mapでループする中身の一番外側にkeyを設定するとエラーが出なくなります。
<div>
{allCategoryPost.map((categoryItems) => {
return (
<div key={categoryItems.cateNo}>
<MenuParts
categoryItems={categoryItems}
currentName={currentName}
contentsPath={contentsPath}
/>
</div>
);
})}
</div>
一番上の例では、MenuParts内にkeyを入れてもエラーが消えないんですよね。終了タグの省略形だとダメみたいです。
MenuPartsにkeyを記述する場合、以下だと一応エラーは出なかったです。
<div>
{allCategoryPost.map((categoryItems) => {
return (
<MenuParts
key={categoryItems.cateNo}
categoryItems={categoryItems}
currentName={currentName}
contentsPath={contentsPath}
></MenuParts>
);
})}
</div>
どの書き方がいいんでしょう?
Discussion