Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent component's name in React?

I would like to provide nice error messages for some of my components, like React does, for example:

WARNING: Each child in an array should have a unique “key” prop. Check the render method of MyComponent. See fb.me/react-warning-keys for more information.

This message provides some info about the context of the error. I know I can find it in the debugger, but I want to make debugging easier for me and my fellow programmers.

like image 476
mik01aj Avatar asked Nov 10 '22 16:11

mik01aj


1 Answers

While it's not clear how you'd use this with a Promise component you mentioned in a comment, you could try this:

var componentName = this.constructor.displayName || this.constructor.name || undefined;

It's inspired by this function in the ReactJS code that looks at the constructor to build a name during React element validation.

But, if you want a parent's name, that isn't possible through any documented means and would likely be fragile if you built code depending on a specific internal implementation. It's a one way flow of information so the child doesn't need a link to its parent by way of normal architecture.

If you need the parent name, you'd need to get the value and pass it through children which I'm sure isn't desireable.

like image 198
WiredPrairie Avatar answered Nov 14 '22 21:11

WiredPrairie