Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 686
MonkeyBonkey Avatar asked Nov 12 '15 22:11

MonkeyBonkey


People also ask

How do you get the key from component React?

To get the key index of an element on click in React:Add an onClick event listener to each element. Every time an element is clicked, call the handler function passing it the event and the key index.

How do you use the key 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.

How do I get the key value from the map in React?

To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.


2 Answers

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.

like image 117
Michelle Tilley Avatar answered Sep 30 '22 17:09

Michelle Tilley


Key : this._reactInternalFiber.key

Index : this._reactInternalFiber.index

like image 32
Ghominejad Avatar answered Sep 30 '22 17:09

Ghominejad