Languages

Why can't I use key property in React?

3 points
Asked by:
Lily
548

I have a specific problem, I can't add item.id to the key property:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const ShoppingListItem = (props) => {
  return (
    <p>{props.key} {props.name}</p>
  );
}

const App = () => {
  const list = [{ id: 1, name: 'apple' },{ id: 2, name: 'banana' }];

  return (
    <div>
      {list.map(item =>
        <ShoppingListItem
          key={item.id}
          name={item.name}
        />)
      }
    </div>
  );
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Error from the console:

index.js:1 Warning: ShoppingListItem: `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)
    at ShoppingListItem (http://localhost:3000/static/js/main.chunk.js:47:22)
    at div
    at App

How to fix this problem?

1 answer
3 points
Answered by:
Lily
548

I found the solution:

We can and we should create a key property for ShoppingListItem elements with unique values to avoid errors.

The thing is we cannot use key as a custom property because it is used by React under the hood, and it is not exposed. The key property is only to help identify element in the DOM.

The solution is to create a new property and assign to it the same value as the key property.

I fixed the problem by adding new id property to the ShoppingListItem - id={item.id} and use {props.id} instead of {props.keys} inside the component.

Example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const ShoppingListItem = (props) => {
  return (
    <p>{props.id} {props.name}</p>
  );
}

const App = () => {
  const list = [{ id: 1, name: 'apple' },{ id: 2, name: 'banana' }];

  return (
    <div>
      {list.map(item =>
        <ShoppingListItem
          key={item.id}
          id={item.id}
          name={item.name}
        />)
      }
    </div>
  );
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

References

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join