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?
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.
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.
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.
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
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