Dynamic Key Generation In Map Function React

A small library providing a utility method to list out React components and generate unique keys automatically

Here on the person component, we're going to say key equals item.name. Save that, and everything is working fine. If we wanted to get a look at how we can further use this JSX generation from a data set, let's say if this.state.filter - we'll need to create that - but if we have a filter, we'll say items equal items.filter. A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated or deleted. In other words we can say that keys are used to give an indentity to the elements in the lists.

Installation

npm install react-keygen --save

Usage

Use reactKeyMap just like you would Array.map. However, no need to worry about finding and passing in a uniq key, reactKeyMap handles that for you!

Each <ListItem /> component will have a uniq key created by hashing our data passed in.If you still wish to use your own keys you can still set it like you normally would, andreactKeyMap will default to the user provided key.

Dynamic

Behind the Curtain

The reactKeyMap utility function hashes the first argument you pass into the callback function, usually this will be an object. It passes this hash value in as the key prop by wrapping our normal map callback function in React.cloneElement.

It uses a 32 bit FNV-1 hash algorithm because FNV algorithms are simple, fast, and maintain a low collision rate. FNV hashes are also great at hashing almost identical strings, which is needed since most of the listed data in this context will be very similar.

Key

FNV Hash Algorithm Advantages

  • Fast
  • Low collision rate
  • High dispersion
  • Simple implementation w/ little overhead

For more details see: http://www.isthe.com/chongo/tech/comp/fnv/

Tests

npm test

Release History

  • 0.1.0 Initial release
  • ReactJS Tutorial
  • ReactJS Useful Resources
  • Selected Reading

React keys are useful when working with dynamically created components or when your lists are altered by the users. Setting the key value will keep your components uniquely identified after the change.

Using Keys

Let's dynamically create Content elements with unique index (i). The map function will create three elements from our data array. Since the key value needs to be unique for every element, we will assign i as a key for each created element.

Dynamic Key Generation In Map Function React 2017

App.jsx

main.js

We will get the following result for the Key values of each element.

Dynamic Key Generation In Map Function React Crossword

If we add or remove some elements in the future or change the order of the dynamically created elements, React will use the key values to keep track of each element.