LoginSignup
1
0

More than 1 year has passed since last update.

ReactでWarning: Each child in a list should have a unique "key" prop.の対処法

Posted at

概要

タイトルのWarningが出たので、対処方法を簡単にまとめました。

問題のコード

column.jsx
return (
  <>
    {tasks.map((task, index) => <Task id={task.id} task={task} index={index}/>)}
  </>
);
task.jsx
const task = props => {
  const {id, task, index} = props
  return (
    <>
    </>
  );
}

警告の内容

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

理由

コンポーネントでkeyを指定していないから

改善策1

以下のように、key=hogehogeを追加する

column.jsx
return (
  <>
    {tasks.map((task, index) => <Task key={task.id} id={task.id} task={task} index={index}/>)}
  </>
);

併せて受け取り側のコードも修正する

task.jsx
const task = props => {
  const {key, id, task, index} = props
  return (
    <>
    </>
  );
}

すると、以下のように別のWarningが表示される

Warning: task: `key` is not a prop. Trying to access it will result in `undefined` being returned.

これは以下の記事で解説しているように、keyを指定しても受け取り側ではundefinedになってしまうという内容。

改善策2

受け取り側で以下のようにkeyを受け取らないようにする。

task.jsx
const task = ({id, task, index}) => {  
  return (
    <>
    </>
  );
}

これで、Warningが出なくなりました。

参考

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