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.
Keys given to the list of elements in React should be unique among the siblings only.
To render empty space in React and JavaScript, we can put the character code for spaces into the code. to add "\u00a0\u00a0" to add 2 spaces between foo and bar.
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used to React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists.
Keys help React identify which items have changed, are added, or are removed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With