Using ES6 Generators to generate keys in React – Hacker Noon

Based on the above, it’s quite obvious how you could use a generator function to dynamically assign keys to elements in a collection. The only thing that such a function has to do is generate a context-unique key for each element. For the sake of generalizing this example for use in other places (e.g. as an element id generator), I am going to make each collection prefix its keys with a unique identifier as well. Here’s my take on the key generator function:

function * Keymaker(listName, ListComponent) {
let keyNum = 0;
while (true) {
let itemKey = `${listName}_${keyNum}`;
yield props => ;

There’s a couple of things happening here, which need to be explained:

  • Due to the fact that the generator function retains a state between calls, keyNum is used in combination with the collection’s prefix (listName) to generate a unique key for each element, then pass it to the element and, finally, increment the value before moving on to the next one.
  • The generator function acts as a wrapper around a component (ListComponent), which is passed by the collection wrapper itself. This allows the generator to be reusable between different lists and collections.

At this point, you might be wondering how to use the Keymaker generator, so here’s a Codepen showcasing its usage:

The only magic happening inside the component is the instantiation of the KeyMaker with a prefix and a component to render for each item, followed by the subsequent calls that map each data object to a keyed element.

That’s all there is to it — 8 lines of code and you can forget about keying objects forever! While this example might be a bit simplistic, you can definitely extend it and tweak it to utilize generator functions in many other intersting ways (generating dynamic, context-unique id values or creating different component types based on context come to mind).

read original article here