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!!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With