A key is required in react map to differentiate the items mapped. So what if key passed is undefined , either it will create unique key for each item or it will assign same undefined ?
CodePudding user response:
If there is no valid key supplied to an item. React will throw an error that a valid key is required. The docs says the following about keys:
"Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:" - https://reactjs.org/docs/lists-and-keys.html#keys
When I have no keys available I use uniqid. This package creates unique ID's that are perfect as key value. See my example below:
import uniqid from 'uniqid';
const fruits = ['banana','apple', 'cherry', 'banana']
fruits.map(fruit => <span key={uniqid()}>{fruit}</span>)
CodePudding user response:
The key attribute is for identification, if you pass no keys or key with undefined value, React will give warning as "Each child in a list should have a unique "key" prop".
But Remember, anytime you want to insert any new element in the middle of the list, the order of the list will not be same and you may see unexpected output/ unnecessary rerendering of items which are having same value as previous render. That is why, React always recommends to add unique keys.
To see undefined key behaviour: https://codesandbox.io/s/great-leakey-crj2dm?file=/src/App.js
CodePudding user response:
If you passed undefined
, it will assign same undefined
for all. And throws an warning
Warning: Encountered two children with the same key,
undefined
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
The easiest way of solving the key problem is to use React.Children.toArray
method. You can wrap your map in React.Children.toArray
and React will do it's thing and pick keys for you! Here is a simple example:
const App = () => {
const arr = ['one', 'two', 'three'];
return (
<>
{React.Children.toArray(arr.map(item => <h3>{item}</h3>))}
</>
);
};
You can also use index
from map
as a key, but it's not recommended.
const App = () => {
const arr = ['one', 'two', 'three'];
return (
<>
{arr.map((item, index) => <h3 key={`${index}`}>{item}</h3>)}
</>
);
};