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.
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.
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.
the ${} is the syntax for variables (or other code to be executed) inside template literals (`).
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.
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.
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