Reputation: 3801
So I understand the unique key: if I have something like:
array.push(<ChildComponent key=some_key />
But if I have something like this:
cols.push(<td key={i}>Some value</td>)>
(While I am creating a table component that has pagination...). I am not sure about that key... That table supports sorting (for columns) so... I believe when we sort, if we use that "i" key, something will be broken. Is in this case, a key necessary? Or it is only necessary in an array that contains child components. In any case, if we don't use a key we get a warning from React that we want to avoid/fix.
Upvotes: 1
Views: 1877
Reputation: 1275
Keys are about state. By state I mean not justthis.state
but also anything you store directly inthis
and need or want to preserve between renders. If your children do not have state, keys do not matter. You could generate a random key every time for each child and that would work. But if some children have state, that approach will create a new child, initialized to its initial state. So if you need to preserve child state between renders the child key cannot change. This will ensure that the child component is preserved rather than recreated.
See Child Reconciliation here: http://facebook.github.io/react/docs/multiple-components.html
Upvotes: 0
Reputation: 3638
If you're looking for a nice solution to generating unique keys, I plucked this one from some of the React/Flux examples and it's worked great for my team and I.
uuid: function () {
var i, random;
var uuid = '';
for (i = 0; i < 32; i++) {
random = Math.random() * 16 | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) {
uuid += '-';
}
uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16);
}
return uuid;
}
Upvotes: 1
Reputation: 86260
Index based keys are sufficient unless:
If any of those are true, you should use a key which identifies the items themselves, rather than their position in the array. Otherwise the index sufficiently identifies it.
Using keys correctly has performance improvements when the subtrees are large or involve img/video/other expensive components. It's also a requirement if you want to animate items being added/removed/reordered correctly.
Upvotes: 2
Reputation: 590
So if I understand you correctly, "i" is some index of the sorted array? If so, that will break down because components should be keyed to something unique to their data (and thus their rendering), not something that is varient like an index.
Because the key isn't consistently tied to the same piece of data, this will simply cause the div's to rerender their contents, as opposed to simply rearranging their order. Try setting key to a hash based on their data!
Upvotes: 1