weak-key
v1.0.3
Published
get a unique key for an object ( mainly for react's key={} )
Downloads
26,419
Readme
weak-key
Get a unique key for an object ( mainly for react's key={} )
install
npm install --save weak-key
usage
var key = require('weak-key');
const todos = [{ text: 'write module' }, { text: 'writes tests' }, { text: 'publish' }];
todos.map(key); // ['weak-key-0', 'weak-key-1', 'weak-key-2'];
todos.reverse().map(key); // ['weak-key-2', 'weak-key-1', 'weak-key-0'];
[{}, {}].map(key); // ['weak-key-3', 'weak-key-4'];
This only works on things that typeof thing === 'object'
so you can't use it on primitive types (numbers, strings, ...)
which makes it great to use for React's key={}
usage with react
import key from 'weak-key';
export default function Todo(items) {
return (
<ul>
{
items.map(item =>
<li key={key(item)}>{item.text}</li>
)
}
</ul>
);
}