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