Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - how to handle keys correctly in reused components

I've recently started with Reactjs and I find it really interesting. Keys are about identity, so identifying each component through a unique key is the way to go, right? Suppose 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)
  );
}));

Note the big IDs numbers. Now, my question is if is better to use numbers as IDs or strings like a hashes as IDs?

Thanks!!

like image 224
Mauro Gava Avatar asked Feb 12 '23 20:02

Mauro Gava


1 Answers

It really doesn't matter, the only thing that matters is that the key is unique among siblings within the parent element. It doesn't have to be unique across your entire app, just inside the parent you're appending these items to.

Often for simple iteration over elements, such as <li> or <option> it's fine to just use the index within 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 this doesn't work well is if you are adding/removing keyed elements in different orders etc later on so that your key might clash with another sibling. In which case you're going to want to generate the key in some other way to make sure it's unique - or use a known unique key from your model. Whichever way you do it as long as it's unique among it's siblings, it'll be fine.

like image 192
Mike Driver Avatar answered Feb 14 '23 08:02

Mike Driver