Ted
Ted

Reputation: 14927

Is there a way to get the Parent components name/displayName from within a Child component?

Long story short, I'm looking to make some error handling more descriptive (like propType validation errors), and was wondering if there's a way to get the name of the parent component doing the boo boo.

For example, the propType validation errors read like so:

Warning: Failed propType: Invalid prop 'label' of type 'number' supplied to 'MyChild', expected 'string'. Check the render method of 'MyParent'.

I'd like my own error to have the parent in it, reading something like:

Error: Instantiation of abstract class 'AbstractMyClass' is not allowed. Check the render method of 'MyParent'.

Is this possible? If it makes a difference, these are written in ES6 syntax.

Thanks in advance! -Ted

Upvotes: 1

Views: 973

Answers (1)

Mauricio Poppe
Mauricio Poppe

Reputation: 4876

You can get the name of function A() {} with A.name, if function B() {} inherits from A then Object.getPrototypeOf(B.prototype) === A.prototype, prototypes should have a link to the constructor through the constructor property i.e. A.protoype.constructor === A

import React, {Component} from 'react'

class AbstractClass extends Component {
  constructor() {
    super()
    if (this.constructor === AbstractClass) {
      throw Error('Instantiation of abstract class AbstractMyClass is not allowed')
    }
  }

  getSuperName () {
    var proto = Object.getPrototypeOf(this) // or this.constructor.prototype
    return Object.getPrototypeOf(proto).constructor.name
  }
}

class A extends AbstractClass {}
class B extends A {}

console.log(new A())                  // works
console.log(new A().getSuperName())   // AbstractMyClass
console.log(new B().getSuperName())   // A

console.log(new AbstractClass())    // throws error

Test it online at http://esnextb.in/?gist=ff5fc627922285b3d085bd9c42420736

Upvotes: 2

Related Questions