Last updated: Feb 29, 2024
Reading timeยท2 min
undefined
The warning "key
is not a prop. Trying to access it will result in
undefined
being returned" is caused when we try to access the key
prop of a
component in React.
To solve the error, pass a prop with a different name to your component.
Here is an example of how the warning is caused.
// โ๏ธ Warning: Header: `key` is not a prop. Trying to access it will result in `undefined` being returned. // If you need to access the same value within the child component, // you should pass it as a different prop. (https://reactjs.org/link/special-props) // ๐๏ธ trying to access key prop const Header = ({key, text}) => { console.log(key); return <h2>{text}</h2>; }; const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; return ( <div> {arr.map((element, key) => { return <Header text={element} key={key} />; })} </div> ); }; export default App;
The issue in the code sample is that we're trying to access the key
prop in
the Header
component.
key
and ref
internally, so it doesn't forward them to the component and trying to access these props returns undefined
.To get around this, we have to use a different name for the prop.
// ๐๏ธ rename key to myKey const Header = ({myKey, text}) => { console.log(myKey); return <h2>{text}</h2>; }; const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; return ( <div> {arr.map((element, key) => { return <Header text={element} key={key} myKey={key} />; })} </div> ); }; export default App;
We renamed the key
prop to myKey
in the Header
component and got rid of
the warning.
key
or ref
, because these are reserved names that React uses internally.React won't forward the values of these props in your components, so trying to
access them returns an undefined
value.
Make sure the key
prop is unique, otherwise, you'll get the
Encountered two children with the same key
warning.
If you use TypeScript, you would have to type the myKey
and text
props.
import React from 'react'; interface HeaderProps { myKey: number; text: string; } // ๐๏ธ rename key to myKey const Header: React.FunctionComponent<HeaderProps> = ({ myKey, text, }) => { console.log(myKey); return <h2>{text}</h2>; }; const App = () => { const arr = ['Austria', 'Belgium', 'Canada']; return ( <div> {arr.map((element, key) => { return <Header text={element} key={key} myKey={key} />; })} </div> ); }; export default App;
You can learn more about the related topics by checking out the following tutorials: