32

I just don't see it explicitly mentioned in the React docs for Lists and Keys.

My instinct was to treat them like HTML ID-attribute-safe, which the HTML5 spec says:

The value must not contain any space characters

... also MDN docs.

I was afraid that a worst-case might be that Keys like ice box, ice cream, and ice cold might accidentally get turned into three keys of ice, which is obviously not what we want.

However, I realize that this isn't HTML. The most specific mention is in the Lists And Keys docs page says

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

So, is it safe to use any "unique string", including whitespace?

I am aware that unique item IDs are best, but in my specific use-case I do not have such a thing, nor a slug/safe string. This stemmed from discussion on the extent to which one should avoid using indexes as keys when real IDs aren't available.

anonymous coward
  • 12,594
  • 13
  • 55
  • 97
  • using indexes as keys is safe in many circumstances though. – Sulthan Oct 13 '17 at 17:35
  • 3
    As far as I know, the key can contain any character. React is clever enough to deal with spaces or any special characters. Since it uses keys only to identify objects, it should treat them as a black box. Only bad code cannot deal with spaces. Usually the key won't be even visible in the resulting HTML therefore HTML rules definitely do not apply. – Sulthan Oct 13 '17 at 17:42
  • 1
    @Sulthan Is there a reason you did not post your response as an answer? I'd be happy to mark it as accepted, based on other feedback and observations since originally posting. – anonymous coward Oct 17 '17 at 01:31

1 Answers1

34

In general, React does not care what characters are inside the string, it does not need to check. React uses the keys when checking uniqueness in the virtual DOM and the keys do not appear in the resulting HTML (any more). Therefore no HTML rules, especially not the ones defined for id apply here.

Why identifiers in HTML do not allow spaces? The reason is probably because they are used in CSS as #myIdentifier and spaces there would make the meaning ambigious.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • In languages that are tokenized by blank space, allowing spaces in identifiers would introduce considerable ambiguity during parsing. This is also why identifiers are usually not allowed to have other magical separator characters (ie. <,>,=) – le3th4x0rbot Feb 13 '19 at 00:56