How to access the "key" property from a reactjs component
How can I access the key
property of a component. I thought it would be in this.props but it's not.
e.g.
<ProductList
key = {list.id}
listId = {list.id}
name = {list.name}
items = {list.items}
/>
and in product list if I do
console.log(this.props)
returns
Object {listId: "list1", name: "Default", items: Array[2]}
With no key property at all. I can create another property and assign the same value to it, but it seems redundant since the key property is already being used.
Also, does the key property have to be unique in the entire component, or just in the loop or collection it's being rendered from?
The key
property is used by React under the hood, and is not exposed to you. You'll want to use a custom property and pass that data in. I recommend a semantically meaningful property name; key
is only to help identify a DOM node during reconciliation, so having another property called listId
makes sense.
The key
property does not need to be unique for the whole component, but I believe it should be unique for the nesting level you're in (so generally the loop or collection). If React detects a problem with duplicate key
s (in the development build), it will throw an error:
Warning: flattenChildren(...): Encountered two children with the same key,
.$a
. Child keys must be unique; when two children share a key, only the first child will be used.
Key : this._reactInternalFiber.key
Index : this._reactInternalFiber.index