Skip to content

Instantly share code, notes, and snippets.

@ironboy
Last active December 28, 2022 15:40
Show Gist options
  • Save ironboy/3ae7dbe3dc9137f565de68dd42742bf1 to your computer and use it in GitHub Desktop.
Save ironboy/3ae7dbe3dc9137f565de68dd42742bf1 to your computer and use it in GitHub Desktop.
Auto create keys in React lists
// Omits the need to write 'key={someUniqueKey}'
// for elements in list when mapping them to jsx
// - automatically tries to get the key from id or _id,
// if not possible, uses the array index instead
let ap = Array.prototype;
if (!ap._mapNoAutoKey) {
let org = ap._mapNoAutoKey = ap.map;
ap.map = function (...args) {
// get ids/unique keys
let ids = org.call(this, (x, i) => x ? (x.id || x._id || i) : i);
console.log(ids)
// apply map
let result = org.apply(this, args);
// patches with key if React element
return org.call(result, x =>
x && x.$$typeof && x.key === null ? { ...x, key: ids.shift() } : x
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment