How to access the "key" property from a reactjs component

Reactjs

Reactjs Problem Overview


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?

Reactjs Solutions


Solution 1 - Reactjs

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 keys (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.

Solution 2 - Reactjs

Key : this._reactInternalFiber.key

Index : this._reactInternalFiber.index

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMonkeyBonkeyView Question on Stackoverflow
Solution 1 - ReactjsMichelle TilleyView Answer on Stackoverflow
Solution 2 - ReactjsGhominejadView Answer on Stackoverflow