LoginSignup
1
0

More than 1 year has passed since last update.

ReactでWarning: task: `key` is not a prop. Trying to access it will result in `undefined` being returned.の対処法

Last updated at Posted at 2022-06-18

概要

Reactでkey={hogehoge}としてコンポーネントに値を渡すとundefinedとなってハマったので、原因と解決策をまとめました。

問題

コード

key="test"として、Column.jsに値を渡します。

App.js
import React from 'react';
import Column from './Column';

const App = () => {
  return (
    <Column key="test"/>
  );
}

export default App;

keyの値を表示してみます。
期待する値は"test"です。

Column.js
import React from 'react';

const Column = props => {
  console.log(`key = ${props.key}`);
  return (
    <></>
  );
}

export default Column;

結果

以下のように、undefinedとなります。

key = undefined

解決策

keyではなく別の名前でColumn.jsに値を渡す必要があります。
Reactの公式ドキュメントにも以下記載がありました。

Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.

要は、keyrefはReact内で使われる特別な値でコンポーネントに値は渡されないということのようです。

コード

以下のようにmyKeyとしてコンポーネントに値を渡してみます。

App.js
import React from 'react';
import Column from './Column';

const App = () => {
  return (
    <Column myKey="test"/>
  );
}

export default App;

Column.jsではprops.myKeyとして値を表示します。

Column.js
import React from 'react';

const Column = props => {
  console.log(`myKey = ${props.myKey}`);
  return (
    <></>
  );
}

export default Column;

結果

以下のように値の受け渡しができました。

myKey = test

参考

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