Languages
[Edit]
EN

React - why not to use key as custom property

0 points
Created by:
starcraf35
754

In this article, we would like to tell you why you shouldn't use key as a custom property in React.

Wrong use example

Below we present a situation where we assign key property to a component using map() method and we want to display the key property inside the component.

Practical 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.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);

Solution

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

In below example, we add new id property to the ShoppingListItem - id={item.id} and use {props.id} instead of {props.keys} inside the component.

Practical 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);

Note:

The post was based on a question - Why can't I use key property in React?

References

Alternative titles

  1. React - why not to read key property
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.

ReactJS

React - why not to use key as custom property
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