Reactjs - how to properly handle keys in reusable components

I recently started working with Reactjs and I am very interested in this. Keys are about identity, so defining each component with a unique key is the way to go, right? Let's say I have this example:

var fruits = [
  {'fruitId': 351421, 'fruit': 'banana'},
  {'fruitId': 254134, 'fruit': 'apple'},
  {'fruitId': 821553, 'fruit': 'orange'}
];

React.DOM.ul(null, fruits.map(function(item) {
  return (
    React.DOM.li({
      key: item.fruitId
    }, item.fruit)
  );
}));

      

Pay attention to the large identification numbers. Now, my question is, is it better to use numbers as identifiers or strings like hashes as identifiers?

Thank!!

+3


source to share


2 answers


It doesn't really matter, the only thing that matters is that the key is unique among siblings in the parent. It doesn't have to be unique across your entire application, just within the parent to which you add these elements.

Often, for simple iteration over elements, for example <li>

or <option>

, just use the index in your iterator.

EG:



var options = [];
for (var i=0; i<this.props.options.length; i++) {
    var option = this.props.options[i];
    options.push(
        <option key={i} value={option.value}>{option.name}</option>
    );
}

      

The only time it doesn't work is if you add / remove items with keys in different orders, etc. later so that your key can collide with another sibling. In this case, you will want to generate the key in some other way to ensure that it is unique - or use a known unique key from your model. Whichever way you practice, as long as he is unique among his brothers and sisters, everything will be fine.

+5


source


As @Mike points out, they are only used to preserve the order of the real DOM elements if you add / remove from the list. They only need to be unique to the local component, so you can reuse natural identifiers from your data. Because of this, I would not use the index from the iterator.



Re. numbers, vs strings: If you're concerned about performance, I would use whatever type you already have. Any conversion / parsing you do will be done on every render. However, that would be pretty low on my list of performance problems in my application.

+2


source







All Articles