1.1.0 • Published 12 months ago

react-key-from-object v1.1.0

Weekly downloads
-
License
LGPL-3.0-or-later
Repository
github
Last release
12 months ago

react-key-from-object

Generate react keys from objects / functions ... anything

Goal

When using lists in React you need to use keys on items to let React know which array item is associated with which visual.

To do that you have to specify a unique string as a key prop.

Let's consider you have this array:

const dogs = [
  { name: "Perle", age: 2 },
  { name: "Tenor", age: 10 },
  { name: "Perle", age: 12 },
];

So we would have a React list looking like this:

<ul>
  {dogs.map((dog) => (
    <li key={dog.name}>
      {dog.name}
      -
      {dog.age}
    </li>
  ))
</ul>

The problem here is our dog "names" are not unique ... So we would need to generate a unique ID for every dog.

In some situations, this is tedious ... that's where react-key-from-object comes in!

<ul>
  {dogs.map((dog) => (
    <li key={keyGen.getKey(dog)}>
      {dog.name}
      -
      {dog.age}
    </li>
  ))
</ul>

This will associate a unique key for your object (without mutating it).

Want to know how it works? Have a look to the source code, it's really tiny!

When NOT to use it

You MUST NOT use this library if you need to rely on react reconciliation (So if you are using server side rendering for instance)

How to use

The hook way (recommended)

import { useKeyGen } from 'react-key-from-object'

const DogList = () => {
  const keyGen = useKeyGen();

  return (
    <ul>
      {dogs.map((dog) => (
        <li key={keyGen.getKey(dog)}>
          {dog.name}
          -
          {dog.age}
        </li>
      ))
    </ul>
  );
}

The "classic" way

import ReactKeyGen from 'react-key-from-object'

const keyGen = new ReactKeyGen()

const t = {};
const u = {};

keyGen.getKey(t); // keyGen_0
keyGen.getKey(u); // keyGen_1
keyGen.getKey(t); // keyGen_0
keyGen.getKey({}); // keyGen_2
1.1.0

12 months ago

1.0.2

2 years ago

1.0.3

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago