Using ES6 Generators to generate keys in React

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 => <ListComponent key={itemKey} {...props} />;
keyNum++;
}
}

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).

Facebook Comments

More Stuff

Building a Polyfill for React Suspense The best way to understand a software concept is to try and build it yourself.?—?TBIf you love React, you’ve probably heard something about the up...
Service Workers On my train journey way back home, I was amazed over the number of apps I have in my phone and that, I’ve different apps to serve my disparate deman...
Create a simple calculator app in React Today we’ll be creating a new react app, a calculator. While the operations are very simple, it’s a bit of struggle to fix things in place and maint...
Simple Recipe to Build a Theme App in React Native Recently, I have been working on a React Native application that demands a changeable theme based on the user selection. I wanted to do this in a simp...
Spread the love

Posted by News Monkey