Skip to content

Instantly share code, notes, and snippets.

@naholyr
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naholyr/f24b23f86963a1dd355e to your computer and use it in GitHub Desktop.
Save naholyr/f24b23f86963a1dd355e to your computer and use it in GitHub Desktop.
React trivial keys

See the discussion

Before (not good):

return <ul>{ paragraphs.map(p => <li>{ p }</li>) }</ul>;
// Each child in an array should have a unique "key" prop. Check the render method of RoomSpace. See http://fb.me/react-warning-keys for more information.

Uglier (not sure better):

return <ul>{ paragraphs.map((p, i) => <li key={ i }>{ p }</li>) }</ul>;

After (better?):

return <ul>{ keys(paragraphs, p => <li>{ p }</li>) }</ul>;
'use strict';
// React-friendly map:
// returns an object indexed on array indices instead of an array
// so that React automatically uses that as keys
function keys (array, transform) {
if (!transform) {
transform = identity;
}
return array.reduce(function (object, value, index, array) {
object["K" + index] = transform(value, index, array);
return object;
}, {});
}
function identity (v) {
return v;
}
module.exports = keys;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment