1

I'm trying to render a fixed size array of non unique integers. The list sometimes changed by user interaction. Which keys should I use? I tried to use map method with map index as keys but since the array indices are not changed the new values are not rendered.

render() {
    const values = this.props.nonUniqueNumbers.map((number, index) =>
        <div key={index}>{number}</div>
    );
    return (
        <div>
            { values }
        </div>
    );
}
user1116377
  • 629
  • 3
  • 15
  • 31

2 Answers2

1

As I have already commented the key is a unique representation of the given object (value entry). Your array has only numbers and no unique key, so a combination of the index and the number is a suitable key in my opinion

<div key={index + '_' + number}>{number}</div>

PS: this {index + number} is obviously not a good key because 0 + 5 = 5 = 2 + 3

Dimitri L.
  • 4,499
  • 1
  • 15
  • 19
0

I tried to use map method with map index as keys but since the array indices are not changed the new values are not rendered.

Using the index of the array should work just fine as the key is used to help optimise the rendering during the reconciliation of the virtual DOM, not to exclude existing items from re-rendering.

It is even in the React documentation as a last resort if you don't have a more consistent key to use.

Michael Peyper
  • 6,814
  • 2
  • 27
  • 44
  • thanks Michael, but it's just not working. The numbers are not updated – user1116377 Apr 18 '17 at 13:25
  • Check [this jsfiddle](https://jsfiddle.net/298na4ps/). It most certainly does change the output when only using the index as the key. If it's not working in your code, I would suggest there is another issue and the props are not actually changing in your component. – Michael Peyper Apr 18 '17 at 13:36
  • @user1116377 I've also [done one which uses your exact code](https://jsfiddle.net/hu0cx3wb/), just to make sure it wasn't a weird props vs. state thing (or something). – Michael Peyper Apr 18 '17 at 13:45