React requires that you have a unique key
attribute on elements in an array. The React docs recommend using an id
from your data. If you don't have an id
then you can use the array index as a "last resort", with the caveat that using an index can cause performance issues when the items can be re-ordered. I've also had some annoying issues when building an array of elements from multiple source arrays and multiple calls to .map()
, each with different transformations, in which case the array indexes won't be unique anyways.
I've started throwing the following boilerplate into my components:
constructor(props) {
super(props);
this.getId = this.getId.bind(this);
this.id = 0;
}
getId() {
return this.id++;
}
which can be used like so:
render() {
const items = this.props.greetings.map(text => ({
<li key={this.getId()}>{text}</li>
}));
return (
<ul>
{items}
</ul>
);
}
This is simple, fast, and doesn't have the issues that using the array index has, but I don't know if there are any issue with this approach or better alternatives that I'm overlooking. Is this bad practice? Are there any other simple ways of generating key
s that don't have the array index issues?