This.key in React.js 0.12

With the release of version 0.12 this.props.key is no longer available inside a component, however it sounds like you can simply replace that with this.key and everything should work as expected.

From the React v0.12 docs:

This means that you need to rename: someElement.props.key -> someElement.key

However when I try to access this.key within the render() function of my component, i get an undefined.

See my pen to illustrate the issue:


Instances of a React Component are created internally in React when rendering. These instances are reused in subsequent renders, and can be accessed in your component methods as this.

How am I supposed to access a component's key?


There is this issue on GitHub that clarifies a lot. Thanks to HEAP for mentioning it.



What the docs actually recommend (although it's badly worded) is that you should treat key and ref as internal to React and not accessible inside the component. If you need to know the key, simply pass it as another property with a different name and then access it on this.props as normal.

Quote from above:

You can no longer access this.props.ref and this.props.key from inside the Component instance itself. So you need to use a different name for those props.

An example would be:

<MyComponent key={foo} reactKey={foo} />

Then accessing inside as this.props.reactKey.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.