0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactでよく出る"Each child in a list should have a unique key prop" のエラー対応

Posted at

はじめに

Reactのmapで配列をループさせた時に、よく同じエラーが出ていたので備忘のために残しておきます。

問題

一意の「キー」プロパティが必要です。と怒られていますね。

Each child in a list should have a unique "key" prop.

Reactは、リストの子要素が変更されたときに、どの要素が追加・削除・更新されたのかを高速に判断するためにkeyを使います。
keyがないと、仮想DOMの差分計算が正確にできず、値が更新出来なくなるためkeyは必須になります。
なのでkey は要素を取得する為に一意でないといけません。

解決方法

ReactがDOM操作の時に判断するために一意のkeyを設定してあげればOKです。
todo.idのように一意のキーが存在しない場合は、ライブラリを使用してuuid等の生成を行う必要があります。

import React from "react";
import Todo from "./Todo";

const TodoList = ({ todos }) => {
  return (
    <div>
    //エラー
      {todos.map((todo) => (
     <div>todo.name</div>
      ))}
    //OK
      {todos.map((todo) => (
     <div key={todo.id}>{todo.name}</div>
      ))}
    </div>
  );
};

export default TodoList;

おわりに

仮想DOMでリアルなDOMとの差分を検知しているので、要素を特定するために一意である必要があるのは当たり前といえば当たり前でしたね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?