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.
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:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const ShoppingListItem = (props) => {
6
return (
7
<p>{props.key} {props.name}</p>
8
);
9
}
10
11
const App = () => {
12
const list = [{ id: 1, name: 'apple' },{ id: 2, name: 'banana' }];
13
14
return (
15
<div>
16
{list.map(item =>
17
<ShoppingListItem
18
key={item.id}
19
name={item.name}
20
/>)
21
}
22
</div>
23
);
24
}
25
26
const root = document.querySelector('#root');
27
ReactDOM.render(<App />, root);
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:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const ShoppingListItem = (props) => {
6
return (
7
<p>{props.id} {props.name}</p>
8
);
9
}
10
11
const App = () => {
12
const list = [{ id: 1, name: 'apple' },{ id: 2, name: 'banana' }];
13
14
return (
15
<div>
16
{list.map(item =>
17
<ShoppingListItem
18
key={item.id}
19
id={item.id}
20
name={item.name}
21
/>)
22
}
23
</div>
24
);
25
}
26
27
const root = document.querySelector('#root');
28
ReactDOM.render(<App />, root);
Note:
The post was based on a question - Why can't I use key property in React?