Home > Back-end >  How to create random key in React?
How to create random key in React?

Time:11-07

Each element in list must have a unic key. So how can create this key?

I did function which return keys like this:

  1. QV8938
  2. XN0210
  3. DC7389
  4. DC8376
  5. HA8357 etc. With random. Is it normal to create such keys?

CodePudding user response:

Is it normal to create such keys?

No, and it's not a good idea. Read the Lists and Keys documentation.

There are three separate problems with random keys:

  1. If they're random, you might end up with the same key on more than one item. (You can mitigate this problem with a sufficiently-powerful random generator like ones used for GUIDs, though.)

  2. You'll cause unnecessary work committing to the DOM for something that hasn't actually changed when its key changes.

  3. You'll cause display errors by not re-committing to the DOM when something does change but its key doesn't change.

Instead, derive your keys from the data for the items being displayed, which is always possible, even if it means you have to create artificial keys for them and then reuse those artificial keys.

You might be tempted to use array indexes as keys. That's not a good idea either in almost any case (that post is linked from the documentation above). The only exception is a static array of static items — nothing in it is ever modified, nor does its order ever change; in that one case, using the index as a key is okay.

  • Related