[React] Unique keys for array of elements with order change

Hi Freecodecamp,

I am working on a project which renders a string as a series of lines (divs). This content may be modified either by shifting rows up/down or by editing the contents of the lines themselves.

I would like to generate a unique key that can also be tied to the content in the interest of best practice. I’m aware using the index is an anti-pattern, as well as the fact that the order changes in my case so it’s not an accurate predictor of identity.

I do not know what the content will be beforehand, so I cannot just assign a static id. In most scenarios I was using the contents of the lines themselves as keys; however, this does not work for empty lines or other commonly occurring lines.

Any thoughts are greatly appreciated.

Hello and welcome to the forum :grin:!

I would use a UUID library :stuck_out_tongue: or this function from stackoverflow:

function uuidv4() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)

// 9697ec71-3e71-4181-93c8-01dfd8259615

How will this ensure I am not re-assigning a new key when I re-render. I am beginning to think I am simply working with the wrong data structure here. I was keeping everything as a single line of text and splitting only at the render. I think I will have to split before the render and generate the keys beforehand so that I can keep a reference to the key the first time I generate it.

Was hoping to avoid this though given it’d be a considerable rewrite.

That would be a problem :sweat:.

Maybe using an object array with the key and content (some kind of Map<UUID, Content>) where you would sort the array whenever the user alters the order?

1 Like

Ok, a rewrite it is! An object array makes more conceptual sense here anyway, even though it was initially more difficult to work with when searching through the content. Thanks skaparate!

1 Like