weak-key
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

weak-key

Get a unique key for an object ( mainly for react's key={} )

NPM version Build status Test coverage Downloads

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>
  );
}

Readme

Keywords

Package Sidebar

Install

npm i weak-key

Weekly Downloads

10,329

Version

1.0.3

License

MIT

Unpacked Size

3.54 kB

Total Files

6

Last publish

Collaborators

  • kolodny