Fix - Key is not a prop. Trying to access it will result in `undefined`

avatar

Borislav Hadzhiev

Mon Apr 18 20222 min read

banner

Photo by Marc Bombenon

Fix - Key is not a prop. Trying to access it will result in 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.

key is not a prop trying to access it results in undefined

Here is an example of how the warning is caused.

App.js
// ⛔️ 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.

React uses props like 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.

App.js
// 👇️ 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.

Make sure to not name props you're trying to access as 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.