I'm trying to set the displayName
property of this class that extends React.Component
. The React docs say that displayName
is a property, so it possible to set it in the constructor? Here's what I'm trying:
class TestUI extends React.Component {
constructor(){
this.displayName = 'CustomTestUI'
}
}
But the library I'm using (pacomo) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless components MyClass.displayName = 'Test' which also doesn't have an effect.
Edit: The answer is: static displayName = 'CustomTestUI'
As stated in the comments, displayName
should be set on the class as a static variable and not an instance using this
.
class TestUI extends React.Component {
static displayName = 'CustomTestUI';
...
}
Here are a couple of examples of where React retrieves displayName
from the component class in this error and this function.
You can also set the displayName
of a component via Component.displayName = 'myName'
.
class TestUI extends React.Component {
...
}
TestUI.displayName = 'CustomTestUI';
The comments and answers given should suffice, however I thought it a good opportunity to describe why your initial attempt did not work (and why it would have been a bad idea anyways).
When working with classes, you have the class "constructor" which is used to create many class "instances". Inside your class methods, all references to this
refer to the class instance. You can always access the constructor by doing this.constructor
.
So the following would have worked, though it is very bad practice for an instance to change a property on its constructor - DO NOT DO THIS:
class TestUI extends React.Component {
constructor(){
// DO NOT DO THIS (for educational purposes only - see other answers)
this.constructor.displayName = 'CustomTestUI'
}
}
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