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

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

A dead simple Webpack 4 example with vanilla JavaS... Grab the repo here! This is a response to a Stack Overflow question. I figured out that there are people out there that may need this, even though...
The Good and the Bad of .NET Framework Programming .NET is a software development framework and ecosystem designed and supported by Microsoft to allow for easy desktop and web application engineering....
Setup storage upload from Browser in 3 step Setup storage upload from Browser in 3 stepAfter giving a try to Firebase authentication modules (surprised to such handy utils), I played aro...
A Practical solution for CORS (Cross-Origin Resour... Summary: I provide a practical solution for solving CORS issue in WKWebView in Ionic and Cordova. The solution works both for iOS and Android. Image ...
Spread the love

Posted by News Monkey