React dynamic Keys when re-rendering

I have an array of objects, I map through the array and return a component for each.

Now, I for various reasons, I cant use the ID or the index as a unique key, so I'm using the short id library, the issue is that every time anything changes and it rerenders the array all the components get new Id's and the It loses focus since the Id changed

 { => (
            <PropertyForm key={shortid.generate()}/>

This is my code, every time a specific property changes it gets rerendered and therefore regenerating its key.

Anu hint would be appreciated, Thanks

1 answer

  • answered 2019-07-10 22:47 Antonio

    Before rendering, you have to generate a unique id for each object to avoid it. More precisely, when an individual object is added to the array, it must generate a unique id of that new Object.

    If you do not change the size or order of the object after the initialization of the array, you can use the key parameter of the map function.

     {, key) => (
                <PropertyForm key={key}/>

    But it is unsafe when it is mutable and I encourage you to follow the way of the former.