Last active
December 28, 2022 15:40
-
-
Save ironboy/3ae7dbe3dc9137f565de68dd42742bf1 to your computer and use it in GitHub Desktop.
Auto create keys in React lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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