Home > Blockchain >  React: Is it okay to use React.Children.toArray to fix each child in a list should have a unique &qu
React: Is it okay to use React.Children.toArray to fix each child in a list should have a unique &qu

Time:02-22

In Reactjs is it okay to use React.Children.toArray method to fix the warning:

Warning: Each child in a list should have a unique "key" prop.

For example:

React.Children.toArray(myArray.map(value => <div>{value}</div>));

the code above seems to fix the warning but I wonder if it is a good practice

CodePudding user response:

No, that's not good practice. The reason react gives a warning that keys are needed is that react needs the keys to tell which element corresponds to which between renders. Your code won't help react to achieve that, so you're just covering up the problem, and not fixing it.

Ideally, if your array of data contains unique ids, you should use those as the keys:

hypotheticalArray.map(data => <div key={data.id}>{data.value}</div>);

If there aren't unique ids, then index can be used as a last resort, but it will misbehave if you change the order of the array.

myArray.map((value, index) => <div key={index}>{value}></div>);

CodePudding user response:

use this instead .

myArray.map((value,index) => <div key={index}  >{value}</div>)

key in react element(child) is added inorder to keep uniqueness of the children, keys are generally used in a list of childrens. If any of the child element changes then key prop helps react which children did got changed as it would have a unique key prop .

CodePudding user response:

React.Children.toArray(myArray.map(value => <div key={value.id}>{value}</div>));


 here you give like this key pass as unique value
  • Related