Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When working with lists and keys in React, can Keys contain whitespace/spaces?

Tags:

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.

like image 534
anonymous coward Avatar asked Oct 13 '17 17:10

anonymous coward


People also ask

What is true for the keys given to a list of elements in React?

Keys given to the list of elements in React should be unique among the siblings only.

How do you add a whitespace in React?

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.

What are list and keys in ReactJS?

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.

What is the point of using keys in React?

Keys help React identify which items have changed, are added, or are removed.


1 Answers

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.

like image 61
Sulthan Avatar answered Oct 13 '22 16:10

Sulthan