weak-key

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

Usage no npm install needed!

<script type="module">
  import weakKey from 'https://cdn.skypack.dev/weak-key';
</script>

README

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