0

My prop is arrays: [[], [], []] with each inner array containing objects with different values. I'm mapping over the array, then passing the inner arrays to another component like so (really dumbed down example),

{arrays.map(values => <div key={???}><InnerComponent values={values} /></div>)}

I'm getting the warning about a unique key, but I can't think of a great way to derive a key other than stringify, which seems really heavy-handed. The user can add/remove items, so index isn't a good solution.

Yatrix
  • 13,361
  • 16
  • 48
  • 78

2 Answers2

1

Instead of passing down an array of arrays, pass down an object of objects instead, generating random unique keys for the objects, and use that for the key. Something like

// https://stackoverflow.com/q/105034
function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

and instead of

[
  [
    value1,
    value2,
    value3
    // ...

make

{
  <randomUUID>: {
    <randomUUID>: value1,
    <randomUUID>: value2,
    <randomUUID>: value3
    // ...

where a UUID is generated only when a new item is generated, or on mount - once an item is paired with a UUID, it should stay paired until the item is deleted.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-3

Just add index value => ... key={???} (value, index) => key={index}