Generate react keys from objects / functions ... anything
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!
You MUST NOT use this library if you need to rely on react reconciliation (So if you are using server side rendering for instance)
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>
);
}
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