1

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.

4 Answers 4

2

Index based keys are sufficient unless:

  • items are inserted at or removed from anywhere except the end
  • the order of items in the items can change
  • items can be replaced with other items

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Very nice explanation. So let me throw an example: I have an array with 5 fruits (apple, orange, pear, banana and cherry) and I want to put them into an html table. I want to be able to sort this table. For each element in the array (td elements) what would be a suitable key? The hash of the string? What will happen if my table can have repeated elements (like two bananas) ?
If it could have repeated elements, then the name wouldn't work. If it can be sorted and you have potentially repeated elements, then you have ambiguity, and must either get more data or use indexes if you can't. Even wrapping the items in a simple object e.g. {value: fruit, id: String(Math.random())} gives you the ability to distinguish items, and the id is a valid key.
1

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!

2 Comments

Actually, the "i" is the index of a for loop that fills the table. I'm just having troubles finding a key for a simple thing like that. Would be the object (or just the value that goes inside the table row td itself) a good key? I still found the warning a weird one in this case.
@FerranNegre it has to be able to convert to a string, so an object won't work. Anything you know is unique to the item, that can be converted to a string, will work fine.
1

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;
}

Comments

0

Keys are about state. By state I mean not justthis.statebut also anything you store directly inthisand 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.