Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the valid symbols for a React 'key'

Tags:

reactjs

What are the valid symbols for a react key prop as such;

<div key="can i use spaces for example?"></div>

In my case I want to use a URL as the key

const links = [
    {
        label: 'foo label',
        href: 'https://example.com/foo',
    },
    {
        label: 'bar label',
        href: 'https://example.com/bar',
    }
]

links.map(
    link => (<a key={link.href} href={link.href}>{link.label}</a>)
);

Is this valid? I was thinking that I could use some hash function to pass the href through first, but this is a pointless step if any character is guaranteed to be valid in a key value.

The reason I'm asking is that I can't find any example in the doc that uses a non-alpha-numeric character for the key, and also explicitly says that, if you don't have an ID to use as key for the object you're rendering you can hash some part of it to make a key. Although this could be because you shouldn't use very long keys, and should therefor hash the content first to truncate it's size, it seems that the whole documentation implicitly says that only alpha-numeric characters should be used as a key.

like image 231
SomeNorwegianGuy Avatar asked Aug 08 '16 10:08

SomeNorwegianGuy


People also ask

What are the keys in React?

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 use of symbol in React?

Symbols are unique data types and no two Symbols are never equal. This feature opens up one of many possibilities of using them in React applications to run code in child components by passing them as props.

What does ${} mean in React?

the ${} is the syntax for variables (or other code to be executed) inside template literals (`).

Can React keys have spaces?

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.


1 Answers

Requirements for React's key is best described in the documentation for reconciliation

In practice, finding a key is not really hard. Most of the time, the element you are going to display already has a unique id. When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. Remember that the key only has to be unique among its siblings, not globally unique.

So, the key should be unique (amongst its siblings) and stable.

Your example, therefore, is a good fit. Spaces should be fine as well.

like image 56
Davin Tryon Avatar answered Sep 19 '22 18:09

Davin Tryon